如何在python中找到多个不重复的数字?

  • 本文关键字:数字 python python python-3.x
  • 更新时间 :
  • 英文 :


我有一个下面的方法来查找列表中不重复的元素:

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,输出仍然与上面相同。

任何想法?

实际上,当您在第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)
def dupes(a):
s = {}
for ele in a:
if ele not in s:
s[ele] = 1
else:
s[ele] += 1
count = 0
keys = []
for x in s:
if s[x] == 1:
count += 1
keys.append(x)
return 'this is the only non-repeating element value is :', count, 'and the key is :', keys

那太好了。

您可以使用列表推导式获取值为1的所有键。

nondupes = [k for (k,v) in s.items() if v==1]
return 'Non-repeating elements: ' + str(nondupes)

同样,您可以将所有计数代码替换为collections.Counter:

s = Counter(a)

您可以使用count()函数在一行python代码中轻松解决此问题:

l = [4, 7, 4, 5, 7, 6, 5, 6, 10 ,11]
only_one_time = [e for e in l if l.count(e) < 2]
print(only_one_time)

给定的代码返回第一个它遇到的非重复元素。例如,如果输入列表为l = [12, 11, 4, 7, 4, 5, 7, 6, 5, 6, 10],输出为This is dupes: ('this is the only non-repeating element value is :', 1, 'and the key is :', 12)

您可以使用Counter:

简洁地实现上述目标
from collections import Counter
l = [4, 7, 4, 5, 7, 6, 5, 6, 10]
c = Counter(l)
dupes = list(key for key in c if c[key] > 1)
print("This is dupes: ", dupes)

输出:

This is dupes:  [4, 7, 5, 6]

您遇到的问题是,您过早地从函数返回包含第一个重复的字符串。其余的副本丢失。

您已经有了重复项的列表,让我们对数据进行return,以便我们可以将结果的计算与结果的显示分开。

return list(e for e in s if s[e] > 1)

最新更新