检查列表中的所有元素是否唯一 [英] Checking if all elements in a list are unique
本文介绍了检查列表中的所有元素是否唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
检查列表中的所有元素是否唯一的最佳方法(最好是传统方法)是什么?
我目前使用 Counter
的方法是:
我能做得更好吗?
解决方案
不是最高效,但直接简洁:
if len(x) >len(设置(x)):通过 # 做某事
对于短名单可能不会有太大影响.
What is the best way (best as in the conventional way) of checking whether all elements in a list are unique?
My current approach using a Counter
is:
>>> x = [1, 1, 1, 2, 3, 4, 5, 6, 2]
>>> counter = Counter(x)
>>> for values in counter.itervalues():
if values > 1:
# do something
Can I do better?
解决方案
Not the most efficient, but straight forward and concise:
if len(x) > len(set(x)):
pass # do something
Probably won't make much of a difference for short lists.
这篇关于检查列表中的所有元素是否唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文