如何检查列表列表中是否存在元素 [英] how to check if an element exists in a list of lists python
本文介绍了如何检查列表列表中是否存在元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表列表,这些列表与文件中的行相对应,并具有多列.
I have a list of lists that correspond to lines in file, with multiple columns.
[ [col1, col2, col3], [elem1, elem2, elem3], [elem4, elem5, elem6] ]
我想检查(例如)elem3
是否在任何列表中,如果存在,请进入该列表. (确实,我有一个需要检查的内容的列表,所以它可能包含elem3
,elem5
,elem7
...等).
I want to check if (for example) elem3
is in any of the lists, and if it is, go into that list. (really I have a list of things I need to check, so it's a list that probably contains elem3
, elem5
, elem7
.... etc)
推荐答案
您可以执行以下操作:
def in_list(list_of_lists, item):
for list_ in list_of_lists:
if item in list_:
return list_
这是它的递归版本:
def in_list(list_of_lists, item):
if not list_of_lists:
return None
if item in list_of_lists[0]:
return list_of_lists[0]
return in_list(list_of_lists[1:], item)
这篇关于如何检查列表列表中是否存在元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文