简体   繁体   English

如何获得列表中唯一的值?

[英]How can I get the value that is unique in a list?

If there's a list the elements of which are [2,2,3,2,2] . 如果有一个列表,其元素为[2,2,3,2,2] I want to find the element that is unique, which is 3 this time. 我想找到唯一的元素,这次是3

I think I could do this with count() method and a few loops, but I wonder if there are simpler and efficient ways to do this. 我想我可以使用count()方法和一些循环来做到这一点,但是我想知道是否有更简单有效的方法来做到这一点。

You can use collections.Counter : 您可以使用collections.Counter

>>> import collections
>>> l = [2,2,3,2,2]
>>> next(k for k, v in collections.Counter(l).items() if v == 1)
3

Without any modules, you can simply perform xor of all elements to get the unique item. 没有任何模块,您只需对所有元素执行xor即可获得唯一项。

This outputs 0 , if there is no unique item as noted by @KeyurPotdar. 如果没有@KeyurPotdar指出的唯一项,则输出0

l = [2,2,3,2,2]

out = l[0]
for elem in l[1:]:
    out = out ^ elem

print(out)
# 3

You can use Counter and then min , 您可以使用Counter ,然后使用min

In [4]: from collections import Counter

In [5]: x = [2,2,3,2,2]

In [6]: c = Counter(x)

In [7]: min(c, key=c.get)
Out[7]: 3

In [8]:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM