简体   繁体   中英

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. 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM