我需要一个函数,它接受一个列表并输出True,如果输入列表中的所有元素使用标准相等运算符计算彼此相等,否则输出False。
我觉得最好是遍历列表,比较相邻的元素,然后与所有结果布尔值。但我不知道最python的方法是什么。
我需要一个函数,它接受一个列表并输出True,如果输入列表中的所有元素使用标准相等运算符计算彼此相等,否则输出False。
我觉得最好是遍历列表,比较相邻的元素,然后与所有结果布尔值。但我不知道最python的方法是什么。
当前回答
我最后写了这样一句话
from itertools import starmap, pairwise
all(starmap(eq, (pairwise(x)))
其他回答
这是一种简单的方法:
result = mylist and all(mylist[0] == elem for elem in mylist)
这稍微复杂一点,它会引起函数调用开销,但语义更清楚地说明:
def all_identical(seq):
if not seq:
# empty list is False.
return False
first = seq[0]
return all(first == elem for elem in seq)
>>> a = [1, 2, 3, 4, 5, 6]
>>> z = [(a[x], a[x+1]) for x in range(0, len(a)-1)]
>>> z
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
# Replacing it with the test
>>> z = [(a[x] == a[x+1]) for x in range(0, len(a)-1)]
>>> z
[False, False, False, False, False]
>>> if False in z : Print "All elements are not equal"
也许我低估了问题的严重性?检查列表中唯一值的长度。
lzt = [1,1,1,1,1,2]
if (len(set(lzt)) > 1):
uniform = False
elif (len(set(lzt)) == 1):
uniform = True
elif (not lzt):
raise ValueError("List empty, get wrecked")
可以使用map和lambda吗
lst = [1,1,1,1,1,1,1,1,1]
print all(map(lambda x: x == lst[0], lst[1:]))
最佳答案
Twitter上有一个不错的帖子,介绍了实现all_equal()函数的各种方法。
给定一个列表输入,最好的提交是:
t.count(t[0]) == len(t)
其他方法
下面是线程的结果:
Have groupby() compare adjacent entries. This has an early-out for a mismatch, does not use extra memory, and it runs at C speed. g = itertools.groupby(s) next(g, True) and not next(g, False) Compare two slices offset from one another by one position. This uses extra memory but runs at C speed. s[1:] == s[:-1] Iterator version of slice comparison. It runs at C speed and does not use extra memory; however, the eq calls are expensive. all(map(operator.eq, s, itertools.islice(s, 1, None))) Compare the lowest and highest values. This runs at C speed, doesn't use extra memory, but does cost two inequality tests per datum. min(s) == max(s) # s must be non-empty Build a set. This runs at C speed and uses little extra memory but requires hashability and does not have an early-out. len(set(t))==1. At great cost, this handles NaNs and other objects with exotic equality relations. all(itertools.starmap(eq, itertools.product(s, repeat=2))) Pull out the first element and compare all the others to it, stopping at the first mismatch. Only disadvantage is that this doesn't run at C speed. it = iter(s) a = next(it, None) return all(a == b for b in it) Just count the first element. This is fast, simple, elegant. It runs at C speed, requires no additional memory, uses only equality tests, and makes only a single pass over the data. t.count(t[0]) == len(t)