15

我有一个如下列表

mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')]

如何查看列表是否包含“value2”?

4

4 回答 4

32

使用any()

any('value2' in sublist for sublist in mylist)
于 2012-10-09T19:31:48.270 回答
10

您可以简单地检查所有子列表any

any('value2' in subl for subl in mylist)
于 2012-10-09T19:31:44.690 回答
3
'value2' in (item for sublist in mylist for item in sublist)
于 2012-10-09T20:01:33.280 回答
0

类似于any(),也支持短路的解决方案:

>>> from itertools import chain
>>> mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')]
>>> 'value2' in chain(*mylist)
True

证明它短路如下any()

>>> it=chain(*mylist)
>>> 'value2' in it
True
>>> list(it) #part of iterable still not traversed
['value3', 'secval1', 'secval2', 'secval3']
于 2012-10-09T19:34:40.077 回答