在同一个列表中迭代两次,以查找不重复的数字

2024-05-18 19:55:06 发布

您现在位置: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 每次我运行它,我只得到虚假的,我不能得到一个真实的声明

我不想使用集合


Tags: the函数inforreturnifisas
1条回答
网友
1楼 · 发布于 2024-05-18 19:55:06

要通过迭代列表两次来解决问题,可以执行以下操作:

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

相关问题 更多 >

    热门问题