python - 确保列表的所有元素都不同的最 pythonic 方法是什么?

标签 python list unique

我有一个用 Python 编写的列表,它是我作为程序的一部分生成的。我有一个强烈的假设,即这些都是不同的,并且我用一个断言来验证这一点。

这是我现在做的方式:

如果有两个元素:

try:
    assert(x[0] != x[1])
except:
    print debug_info
    raise Exception("throw to caller")

如果有三个:

try:
    assert(x[0] != x[1])
    assert(x[0] != x[2])
    assert(x[1] != x[2])
except:
    print debug_info
    raise Exception("throw to caller")

如果我不得不用四个元素来做这件事,我会发疯的。

是否有更好的方法来确保列表中的所有元素都是唯一的?

最佳答案

也许是这样的:

if len(x) == len(set(x)):
    print "all elements are unique"
else:
    print "elements are not unique"

关于python - 确保列表的所有元素都不同的最 pythonic 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1501118/

相关文章:

python - 是否可以在设备上加载 .gpx 轨道以使用 appium 测试跟踪器?

python - 有没有什么很酷的方法在 python 类中表达 `if x is None: x = self.x` ?

c - 没有定义数据存储的链表叫什么?

python - 仅从两个列表中获取唯一元素

python ,nltk : Cannot import mkdtemp

python - 使用 Selenium Python 的复选框

algorithm - 从具有容错性的多个值生成唯一 ID

python-3.x - 在 Pandas 数据框行中保留唯一的单词

python - 将核苷酸转换为相应的 DNA 序列

python - python中的reversed函数是如何实现的?