关于python:如何确定二维列表是否包含值?

How to determined if a 2 dimensional list contain a value?

我有一个如下的清单

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

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


使用any()

1
any('value2' in sublist for sublist in mylist)


您只需使用any检查所有子列表:

1
any('value2' in subl for subl in mylist)


1
'value2' in (item for sublist in mylist for item in sublist)

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

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

证明其短路,如any()

1
2
3
4
5
>>> it=chain(*mylist)
>>> 'value2' in it
True
>>> list(it) #part of iterable still not traversed
['value3', 'secval1', 'secval2', 'secval3']