简体   繁体   English

检查所有元素是否都是唯一的不可用列表

[英]Check if all elements are unique with nonhashable list

New to Python here. 这里是Python的新手。 I've figured out that it's rather trivial to check if a list has all unique elements using 我已经发现检查列表是否包含所有唯一元素是相当简单的

  if len(lst) > len(set(lst))

But how would I deal with a case like this? 但是我该如何处理这样的案件呢?

all_different([[],[],[],[]]) #False

I can't use the set() function in this example. 我不能在这个例子中使用set()函数。 I understand how I might do this (rather inefficiently) with nested for loops in Java. 我理解如何使用Java中的嵌套for循环来做这个(相当低效)。 But not sure how I could implement this in Python. 但不确定如何在Python中实现这一点。

You can't hash lists as they're mutable, but you can convert them to tuples, and hash them instead. 您不能散列列表,因为它们是可变的,但您可以将它们转换为元组,并改为散列它们。 Like so: set(tuple(elem) for elem in lst) 像这样: set(tuple(elem) for elem in lst)

Your comparison would then become: 您的比较将变为:

myset = set(tuple(elem) for elem in lst)
if len(lst) > len(myset)

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

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