懒惰的方式来检查所有生成的元素是否相等 [英] Lazy way to check if all generated elements are equal

查看:65
本文介绍了懒惰的方式来检查所有生成的元素是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个产生可比较值的迭代器,这是检查所有结果是否相等的一种惰性方法.即,在不消耗整个发电机的情况下尽快失效.因此 len(set(g))== 1 不起作用.

Given an iterator that yields comparable values, what would be the lazy way to check if all results are equal. That is, fail as soon as possible, without consuming the whole generator. So len(set(g))==1 won't work.

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

I'm looking for a simple expression / combination of library functions. No defs.

推荐答案

由@unutbu给出的表达式

Expression as given by @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

根据要求提早失败.

这篇关于懒惰的方式来检查所有生成的元素是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆