How to determined if a 2 dimensional list contain a value?
我有一个如下的清单
1 | mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')] |
如何查看列表是否包含"value2"?
使用
1 | any('value2' in sublist for sublist in mylist) |
号
您只需使用
1 | any('value2' in subl for subl in mylist) |
1 | 'value2' in (item for sublist in mylist for item in sublist) |
与
1 2 3 4 | >>> from itertools import chain >>> mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')] >>> 'value2' in chain(*mylist) True |
证明其短路,如
1 2 3 4 5 | >>> it=chain(*mylist) >>> 'value2' in it True >>> list(it) #part of iterable still not traversed ['value3', 'secval1', 'secval2', 'secval3'] |
。