简体   繁体   English

在列表列表中查找元素

[英]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.

相关问题 在列表列表中查找共同元素 - finding common elements in list of lists 比较python中列表列表中的元素并找到匹配项 - Compare elements in a list of lists in python and finding a match 通过Python中的元素总和查找列表列表的最大值 - Finding maximum of a list of lists by sum of elements in Python 从列表中嵌入列表的列表中查找元素(Python) - Finding elements from list in lists embedded in list (Python) 在python列表列表中查找包含唯一元素的列表? - Finding list containing unique elements in list of lists in python? Python - 在三个列表中查找相同的元素(忽略空列表) - Python - finding same elements in three lists (ignoring empty list) 从最大分散重复元素的列表列表中找到最佳组合 - Finding the optimal combination from a list of lists that maximally disperses repeating elements 扫描 python 中的列表列表,查找元素上的特定字符 - scan list of lists in python finding specific characters on elements 在python中找到两个列表列表之间的最常用元素的最快方法 - Fastest way of finding common elements between two list of lists in python 从具有列表结构列表和空列表的文本文件中查找列表和元素的总数 - Finding total number of lists and elements from a text file with list of lists structure and empty lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM