首页 > 解决方案 > 遍历同一个列表两次以找到没有重复的数字

问题描述

没有计数功能这是我下面的代码

*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 语句

我不想使用集合

标签: pythonlist

解决方案


要通过迭代列表两次来解决问题,可以这样做:

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

推荐阅读