在任何内置函数中组合两个iterables

时间:2017-11-24 11:30:03

标签: python iterator

所以这是一个普通的any()方法,检查iterable是否在其任何元素中返回True:

list_a = ['test', 'hello']
list_b = ['test', 'bye']
name = 'test'
any(name == item for item in list_a)
True

但是如何组合两个迭代?

这有效:

name = 'hello'
any(name == item_a for item_a in list_a or name == item_b for item_b in list_b)
True

这不是:

name = 'bye'
 any(name == item_a for item_a in list_a or name == item_b for item_b in list_b)
False

这可以简化为:

any([True] or [False]) vs any([False] or [True])

如何转变为:

any([True, False]) or any([False, True])

如何在any()方法中组合这两个迭代器?

3 个答案:

答案 0 :(得分:1)

不确定你想要什么,但这更简单:

any(name == item for item in list_a + list_b)

取2:

从对象获取属性值:

any([any(name==item.get_value() for item in list1), any(name==item.obtain_value() for item in list2)])

它失去了简化因素,所以它并没有真正解决你的问题 它保留了懒惰的评估短路。

答案 1 :(得分:1)

any接受单个可迭代。对于简单列表,您可以执行

any(['hello'=word for word in list1 + list2])

对于其他类型的迭代器,您可以使用itertools.chain从它们生成单个迭代。

在你的情况下,最简单的事情似乎是

if 'hello' in list1 + list2

答案 2 :(得分:1)

list_a设置为具有False真值的内容有助于揭示第一种方法的错误:

list_a = []
any(name == item_a for item_a in list_a or name == item_b for item_b in list_b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'item_b' is not defined

这应该有助于说服您将any行解释为

any(name == item_a for item_a in (list_a or name == item_b) for item_b in list_b)

由于原始示例中的or短路且list_aTrue,因此or name == item_b无效。

您可以通过or两个any语句或itertools.chain any

的操作数来实现您期望的行为
import itertools as it
name = 'bye'
any(it.chain((name==item_a for item_a in list_a), (name==item_b for item_b in list_b)))
# True
相关问题