没有计数功能 下面是我的代码
*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 每次我运行它我只会得到错误,我不能得到一个真正的声明
我不想使用集合
答案 0 :(得分:1)
要通过迭代列表两次来解决问题,可以这样做:
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
确定给定列表是否具有唯一项的其他方法:
方法一:将列表转换为集合,然后比较集合和原列表的项数
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