Python 所有列表值相同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4752294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:21:46  来源:igfitidea点击:

all list values same

pythonlist

提问by derks

In Python, is the a simple way to test that all values in a list are equal to one another?

在 Python 中,是否有一种简单的方法来测试列表中的所有值是否彼此相等?

采纳答案by Mariy

Many ways come to mind. You could turn it in a set(which filters out duplicates) and check for length of oneEdit: As another poster noted, this only works with hashable types; I revoke the suggestion as it has worse performance andis less general.

想到了很多方法。 你可以把它变成一个set(过滤掉重复的)并检查一个的长度编辑:正如另一位海报指出的那样,这只适用于可哈希类型;我撤销的建议,因为它有更糟糕的表现少将军。

You could use a generator expression: all(items[0] == item for item in items), which would short-circuit (i.e. return false as soon as the predicate fails for an item instead of going on).

您可以使用生成器表达式: all(items[0] == item for item in items),它会短路(即,一旦谓词对某个项失败而不是继续执行,则立即返回 false)。

回答by Mariy

>>> l = [1, 1, 1, 1]
>>> all(map(lambda x: x == l[0], l))
True

回答by Greg Hewgill

>>> a = [1, 1, 1, 1]
>>> len(set(a))
1

Note that this method assumes that each element in your list can be placed into a set. Some types, such as the mutable types, cannot be placed into a set.

请注意,此方法假定列表中的每个元素都可以放入一个集合中。某些类型,例如可变类型,不能放入集合中。

回答by AndiDog

Using a setas pointed out by Greg Hewgill is a great solution. Here's another one that's more lazy, so if one pair of the elements are not equal, the rest will not be compared. This might be slower than the setsolution when comparing all items, but didn't benchmark it.

使用setGreg Hewgill 指出的 a 是一个很好的解决方案。这是另一个更懒惰的,因此如果一对元素不相等,则不会比较其余元素。set比较所有项目时,这可能比解决方案慢,但没有对其进行基准测试。

l = [1, 1, 1]
all(l[i] == l[i+1] for i in range(len(l)-1))

Note the special case all([]) == True.

注意特殊情况all([]) == True