给定一个产生可比较值的迭代器,检查所有结果是否相等的懒惰方法是什么。也就是说,尽快失败,而不消耗整个生成器。所以len(set(g))==1
行不通。
我正在寻找库函数的简单表达式/组合。没有def
。
怎么样:
first = next(gen)
if all(x==first for x in gen):
print "They're all the same!"
(Rob Wouters 在评论中描述了这个算法,我只是把它放到 Python 中)
正如 FJ 所发现的,这将在空迭代器上失败,并且假设您已经有了一个iterator,而不仅仅是一个iterable。他的回答解决了这两点。
@unutbu 给出的表达式
all(y == first for first in gen for y in gen)
测试/演示:
>>> def test(*args):
... for a in args:
... print a,
... yield a
...
>>> g = test(1,1,1,1,1,1,1)
>>> print all(a == x for a in g for x in g)
1 1 1 1 1 1 1 True
>>> g = test(1,1,1,2,1,1,1)
>>> print all(a == x for a in g for x in g)
1 1 1 2 False
按要求提前失败。
def all_equal(iterable):
itr = iter(iterable)
try:
first = next(itr)
except StopIteration:
return True
else:
return all(item == first for item in itr)
True
空的可迭代对象from itertools import *
if all(a == b for a, b in izip(gen, islice(gen, 1, None))):
print "They're all the same!"
虽然这对迭代器不起作用。
gen1, gen2 = tee(gen)
next(gen1, None)
if all(a == b for a, b in izip(gen1, gen2)):
print "They're all the same!"
或作为“单一表达式”:
if (lambda g, h: all(a == b for a, b in izip(g, islice(h, 1, None))))(*tee(gen)):
print "They're all the same!"