我有一个如下列表
mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')]
如何查看列表是否包含“value2”?
我有一个如下列表
mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')]
如何查看列表是否包含“value2”?
使用any()
:
any('value2' in sublist for sublist in mylist)
您可以简单地检查所有子列表any
:
any('value2' in subl for subl in mylist)
'value2' in (item for sublist in mylist for item in sublist)
类似于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']