In Python, is the a simple way to test that all values in a list are equal to开发者_运维问答 one another?
Many ways come to mind. You could turn it in a Edit: As another poster noted, this only works with hashable types; I revoke the suggestion as it has worse performance and is less general.set
(which filters out duplicates) and check for length of one
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).
>>> 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.
>>> l = [1, 1, 1, 1]
>>> all(map(lambda x: x == l[0], l))
True
Using a set
as 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 set
solution when comparing all items, but didn't benchmark it.
l = [1, 1, 1]
all(l[i] == l[i+1] for i in range(len(l)-1))
Note the special case all([]) == True
.
精彩评论