检查是否列表中的所有元素都是独一无二的 [英] Checking if all elements in a list are unique

查看:116
本文介绍了检查是否列表中的所有元素都是独一无二的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是检查在列表中的所有元素是否是唯一的最佳方式(最好如在常规方式)?

What is the best way (best as in the conventional way) of checking whether all elements in a list are unique?

使用计数器我目前的做法是:

>>> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆