[英]Finding elements in list of lists
I have a list in a list. 我有一个清单。
I want to find whether it contains an item of interest. 我想查找它是否包含感兴趣的项目。
For example: L=[['READ',[A,B],'2'],['WRITE',[C,D],'2']]
Now, I have a string, str=READ
, I want to iterate over the two lists, including the sub lists to find whether such an element is present. 现在,我有一个字符串str=READ
,我想遍历两个列表,包括子列表以查找是否存在这样的元素。 Is there a way to do it without resorting to using indexes? 有没有办法不使用索引来做到这一点?
I do not want to use indexing because there is no guarantee of the list length remaining same. 我不想使用索引,因为不能保证列表长度保持不变。
Using a common flattening function: 使用通用的展平功能:
import collections
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
You can flatten the list and then check if READ is in it. 您可以展平列表,然后检查其中是否包含“读取”。
>>> 'READ' in flatten(L)
True
Provided there are no loops in the data stucture being searched this is a simple recursive problem: 假设搜索的数据结构中没有循环,这是一个简单的递归问题:
def find(x, L):
return x in L or any(find(x, sublist)
for sublist in L
if isinstance(sublist, list))
if instead there can be loops in the data structure then you must guard against entering infinite recursion 相反,如果数据结构中可能存在循环,则必须防止输入无限递归
def find(x, L, seen=None):
if seen is None:
seen = set()
if id(L) in seen:
# Avoid infinite recursion
return False
seen.add(id(L))
return x in L or any(find(x, sublist, seen)
for sublist in L
if isinstance(sublist, list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.