方法有三:
将列表构造为集合,再判断长度
用一个元素与所有元素比较
比较列表第一个元素的个数和列表长度
Pythonic ways of checking if all
items in a list are equal:
lst = ['a', 'a', 'a']
len(set(lst)) == 1 True
all(x == lst[0] for x in lst) True
lst.count(lst[0]) == len(lst) True
I ordered those from "most Pythonic" to "least Pythonic"
and "least efficient" to "most efficient".
The len(set()) solution is idiomatic, but constructing
a set is less efficient memory and speed-wise.
三个方法的排序,语言地道性由高到低,效率由低到高。构造一个集合就是用内存换速度的。