python - 遍历同一个列表两次以找到没有重复的数字
问题描述
没有计数功能这是我下面的代码
*Testing lists below*
a = [9, 4, 2, 3, 5, 9, 10]
b = [3, 4, -1, 9, 99, 12, 34]
***
def is_unique(a_list): #returns true for no duplicate numbers #returns false other wise
for num1 in a_list: #iterate through list once
for num2 in a_list: #iterate thorough list twice
if num1 == num2: #if num1 is the same as num2
return False
else: #if num1 is not the same as num2
return True
我想表明 is_unique 函数可以遍历同一个列表两次,如果列表没有重复的数字,那么它返回 True 每次我运行它时我只会得到 false,我无法得到 True 语句
我不想使用集合
解决方案
要通过迭代列表两次来解决问题,可以这样做:
a = [9, 4, 2, 3, 5, 9, 10]
b = [3, 4, -1, 9, 99, 12, 34]
def is_unique(a_list):
i = 0
for a in a_list:
i = a_list.index(a, i)
j = 0
for b in a_list:
j = a_list.index(b, j)
if a == b and i != j:
return False
else:
return True
print(is_unique(a))
print(is_unique(b))
输出:
False
True
使用以下代码可以提高上述代码的效率enumerate()
:
def is_unique(a_list):
for i, a in enumerate(a_list):
for j, b in enumerate(a_list):
if a == b and i != j:
return False
else:
return True
确定给定列表是否具有唯一项的其他方法:
方法1:将列表转换为集合,然后比较集合中的项目数和原始列表中的项目数
a = [9, 4, 2, 3, 5, 9, 10]
b = [3, 4, -1, 9, 99, 12, 34]
def is_unique(a_list):
return len(a_list) == len(set(a_list))
方法 2:计算列表中每个项目的出现次数list.count()
def is_unique(a_list):
for a in a_list:
if a_list.count(a) > 1:
return False
else:
return True
推荐阅读
- java - HTTP 状态 406 – 不可接受 [使用 spring 4.3.x + Java 8 从后端流式传输大量数据]
- alexa - Alexa技能中的多轮对话错误
- javascript - 使用 Windows 凭据从节点向另一台服务器发送 POST 请求
- python - 属性错误:错误表示新属性不存在,即使它确实存在
- javascript - 钩子中的延迟状态更改
- javascript - 从外部类调用 Vue 组件内部的方法
- mysql - 如何在使用 Nodejs 将 CSV 数据上传到 mySQL 时修复 DATETIME 截断警告
- ruby - 如何获得 Ruby 解释器堆栈的当前深度?
- solidity - 如果您发送值,则应支付构造函数
- c# - 在 mvc 视图中创建动态按钮