1

给定一个产生可比较值的迭代器,检查所有结果是否相等的懒惰方法是什么。也就是说,尽快失败,而不消耗整个生成器。所以len(set(g))==1行不通。

我正在寻找库函数的简单表达式/组合。没有def

4

4 回答 4

7

怎么样:

first = next(gen)
if all(x==first for x in gen):
    print "They're all the same!"

(Rob Wouters 在评论中描述了这个算法,我只是把它放到 Python 中)

正如 FJ 所发现的,这将在空迭代器上失败,并且假设您已经有了一个iterator,而不仅仅是一个iterable。他的回答解决了这两点。

于 2012-10-19T22:13:06.847 回答
3

@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

按要求提前失败。

于 2012-10-19T22:36:35.643 回答
2
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空的可迭代对象
  • 适用于任何可迭代的,而不仅仅是生成器
于 2012-10-19T22:16:40.793 回答
1
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!"
于 2012-10-20T23:12:08.653 回答