[英]How do I check if all elements in a list are the same?
If i have this list; 如果我有这个清单;
mylist = ['n', 'n', '4', '3', 'w']
How do I get it to read the list, and tell me whether or not they are all the same? 如何让它阅读列表,并告诉我它们是否都是一样的?
I am aware that it is easy to tell they are not all the same in this example. 我知道在这个例子中很容易说出它们并不完全相同。 I have much larger lists I would like it to read for me.
我有更大的列表,我希望它能为我阅读。
Would I go about this using: 我会用这个来解决这个问题:
min(...)
If so, how would I input each list item? 如果是这样,我将如何输入每个列表项?
You can use set like this 你可以像这样使用set
len(set(mylist)) == 1
Explanation 说明
sets store only unique items in them. 集合中只存储唯一的项目。 So, we try and convert the list to a set.
因此,我们尝试将列表转换为集合。 After the conversion, if the set has more than one element in it, it means that not all the elements of the list are the same.
转换后,如果集合中包含多个元素,则表示并非列表中的所有元素都相同。
Note: If the list has unhashable items (like lists, custom classes etc), the set
method cannot be used. 注意:如果列表具有不可用项(如列表,自定义类等),则无法使用
set
方法。 But we can use the first method suggested by @falsetru, 但我们可以使用@falsetru建议的第一种方法,
all(x == mylist[0] for x in mylist)
Advantages: 好处:
It even works with unhashable types 它甚至适用于不可用的类型
It doesn't create another temporary object in memory. 它不会在内存中创建另一个临时对象。
It short circuits after the first failure. 它在第一次故障后短路。 If the first and the second elements don't match, it returns
False
immediately, whereas in the set
approach all the elements have to be compared. 如果第一个和第二个元素不匹配,则立即返回
False
,而在set
方法中,必须比较所有元素。 So, if the list is huge, you should prefer the all
approach. 因此,如果列表很大,您应该更喜欢
all
方法。
It works even when the list is actually empty. 即使列表实际为空,它也能工作。 If there are no elements in the iterable,
all
will return True
. 如果iterable中没有元素,则
all
将返回True
。 But the empty list will create an empty set
for which the length will be 0. 但是空列表将创建一个空
set
,其长度为0。
Using all
and generator expression : 使用
all
和generator表达式 :
all(x == mylist[0] for x in mylist)
Alternative: 替代方案:
mylist.count(mylist[0]) == len(mylist)
NOTE The first will stop as soon as it found there's any different item in the list, while the alternative will not. 注意一旦发现列表中有任何不同的项目,第一个将停止,而替代品则不会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.