我需要一个函数,它接受一个列表并输出True,如果输入列表中的所有元素使用标准相等运算符计算彼此相等,否则输出False。
我觉得最好是遍历列表,比较相邻的元素,然后与所有结果布尔值。但我不知道最python的方法是什么。
我需要一个函数,它接受一个列表并输出True,如果输入列表中的所有元素使用标准相等运算符计算彼此相等,否则输出False。
我觉得最好是遍历列表,比较相邻的元素,然后与所有结果布尔值。但我不知道最python的方法是什么。
当前回答
还有一个纯Python递归选项:
def checkEqual(lst):
if len(lst)==2 :
return lst[0]==lst[1]
else:
return lst[0]==lst[1] and checkEqual(lst[1:])
然而,由于某些原因,它在某些情况下比其他选项慢两个数量级。从C语言的角度来看,我希望这更快,但事实并非如此!
另一个缺点是Python中有递归限制,在这种情况下需要进行调整。比如用这个。
其他回答
def allTheSame(i):
j = itertools.groupby(i)
for k in j: break
for k in j: return False
return True
适用于Python 2.4,它没有“all”。
我怀疑这是“最python化的”,但类似于:
>>> falseList = [1,2,3,4]
>>> trueList = [1, 1, 1]
>>>
>>> def testList(list):
... for item in list[1:]:
... if item != list[0]:
... return False
... return True
...
>>> testList(falseList)
False
>>> testList(trueList)
True
会成功的。
最佳答案
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)
还有一个纯Python递归选项:
def checkEqual(lst):
if len(lst)==2 :
return lst[0]==lst[1]
else:
return lst[0]==lst[1] and checkEqual(lst[1:])
然而,由于某些原因,它在某些情况下比其他选项慢两个数量级。从C语言的角度来看,我希望这更快,但事实并非如此!
另一个缺点是Python中有递归限制,在这种情况下需要进行调整。比如用这个。
lambda lst: reduce(lambda a,b:(b,b==a[0] and a[1]), lst, (lst[0], True))[1]
下一个会短路:
all(itertools.imap(lambda i:yourlist[i]==yourlist[i+1], xrange(len(yourlist)-1)))