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