首页 > 解决方案 > 如何在python中找到多个不重复的数字?

问题描述

我有一个在列表中查找非重复元素的方法:

def dupes(a):
    s = {}
    for ele in a:
        if ele not in s:
            s[ele] = 1
        else:
            s[ele] += 1
    for x in s:
        if s[x] == 1:
            return 'this is the only non-repeating element value is :', s[x], 'and the key is :', x
    return

l = [4, 7, 4, 5, 7, 6, 5, 6, 10]
cd = dupes(l)
print("This is dupes: ", cd)

代码运行成功,输出如下:

This is dupes:  ('this is the only non-repeating element value is :', 1, 'and the key is :', 10)

但是当我尝试在列表中添加多个非重复元素时,输出不会改变。例如,如果我在列表末尾添加 11,则输出仍然与上面相同。

任何想法?

标签: pythonpython-3.x

解决方案


实际上,当您在第 10 行返回时,函数就结束了。这是为了以防您还不了解列表理解,因为许多人已经使用该技术为您提供了解决方案。我只会给你一个简单的解决方案,它将返回一个非重复数字的列表。

def dupes(a):
    s = {}
    non_dupes = []
    for ele in a:
        if ele not in s:
            s[ele] = 1
        else:
            s[ele] += 1
    for x in s:
        if s[x] == 1:
            non_dupes.append(x)
    return non_dupes

l = [4, 7, 4, 5, 7, 6, 5, 6, 10, 11]
cd = dupes(l)
print("This is dupes: ", cd)

推荐阅读