Python查找列表仅出现一次的元素 多结果返回最小值无则返Not found
问题描述
我需要编写函数实现以下逻辑:统计类似[2, 1, 2, 5, 2, 1, 1, 3]的列表中仅出现一次的数字:
- 存在多个仅出现一次的数字时,返回其中最小的数字
- 不存在仅出现一次的数字时,返回
"Not found"
我目前编写的代码如下:
def one_time(nums, n): nums.sort() if nums[0] != nums[1]: print(nums[0], end = " ") for i in range(1, n - 1): if (nums[i] != nums[i + 1] and nums[i] != nums[i - 1]): print( nums[i]) if nums[n - 2] != nums[n - 1]: print(nums[n - 1], end = " ") if __name__ == "__main__": nums = [2, 1, 2, 5, 2, 1, 1, 3] n = len(nums) one_time(nums, n)
现有代码的问题
- 函数直接打印结果,没有按要求做返回值处理
- 末尾元素的判断逻辑写在循环内部,会重复执行多次,输出重复内容
- 没有对所有单次出现的数字做最小值筛选,不符合返回最小数的要求
- 没有覆盖不存在单次出现数字的场景,也没有处理列表长度小于2的边界情况
- 额外传入长度参数
n没有必要,可直接通过内置方法len(nums)获取列表长度
修正方案
基于原有排序思路的修正
保留原本排序后相邻比对的逻辑,修复上述问题:
def one_time(nums): n = len(nums) # 空列表直接返回结果 if n == 0: return "Not found" nums.sort() single_nums = [] # 校验首位元素 if n == 1 or nums[0] != nums[1]: single_nums.append(nums[0]) # 校验中间元素 for i in range(1, n - 1): if nums[i] != nums[i-1] and nums[i] != nums[i+1]: single_nums.append(nums[i]) # 校验末位元素 if n >= 2 and nums[-1] != nums[-2]: single_nums.append(nums[-1]) return min(single_nums) if single_nums else "Not found" if __name__ == "__main__": nums = [2, 1, 2, 5, 2, 1, 1, 3] print(one_time(nums))
运行上述代码,针对给出的测试用例,会正确输出单次出现的数字里最小的3。
更简洁的实现
使用标准库的计数器工具统计频次,代码更简洁,出错概率更低:
from collections import Counter def one_time(nums): num_count = Counter(nums) single_nums = [num for num, cnt in num_count.items() if cnt == 1] return min(single_nums) if single_nums else "Not found" if __name__ == "__main__": nums = [2, 1, 2, 5, 2, 1, 1, 3] print(one_time(nums))
内容的提问来源于stack exchange,提问作者Shashank Dharba
相关产品推荐
相关产品推荐

