开发者

all list values same [duplicate]

开发者 https://www.devze.com 2023-02-05 15:17 出处:网络
This question already has answers here: Check if all elements in a list are identical (29 answers) Closed 6 years ago.
This question already has answers here: Check if all elements in a list are identical (29 answers) Closed 6 years ago.

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 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 and is less general.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消