这里没有计数函数,这是我下面的代码
*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语句
我不想用套
发布于 2021-02-22 01:52:37
要通过两次迭代列表来解决这个问题,可以这样做:
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:将列表转换为set,然后比较来自集合和原始列表的项数
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
https://stackoverflow.com/questions/66308968
复制相似问题