如何确定二维列表是否包含值?

时间:2012-10-09 19:30:23

标签: python list python-2.7

我有一个如下列表

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

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

4 个答案:

答案 0 :(得分:23)

使用any()

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

答案 1 :(得分:8)

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

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

答案 2 :(得分:2)

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

答案 3 :(得分: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']