Im having a little list problem with big lists. Say for example, I have this

Numbers = [["aaa", "bbb", "ccc"] , ["ddd", "eee", "fff"]]

How do I search and return from this list? eg searching for "fff" and returning "ddd"?
I can only return specific position in the list, but pos. 0 is ["aaa", "bbb", "ccc"]...

8 Years
Discussion Span
Last Post by Gribouillis

A way to handle nested lists is to treat them as trees where a list is a node and it's elements are other nodes (lists) or leafs (strings). In a tree (like in a folder tree for example), the position of an element is not given by an index, but by a path. You could use tree handling functions like this

def find_path(tree, leaf, path=None):
    "returns a list of indexes representing a path to a string in a tree of strings"
    if path is None:
        path = []
    for i, t in enumerate(tree):
        if isinstance(t, str):
            if t == leaf:
                return path
            p = find_path(t, leaf, path)
            if p:
                return p
        del path[-1]
    return None

def get_node(tree, path):
    "retrieves a node in a tree of strings from a list of indexes"
    for i in path:
        tree = tree[i]
    return tree

if __name__ == "__main__":
    L = [["aaa", "bbb", "ccc"], ["ddd", "eee", "fff"]]
    print find_path(L, "fff") # prints [1, 2]
    print L[1][2] # prints fff

    L = [["aaa", ["bbb", "ccc"], "ddd"], ["eee", "fff", "ggg"]]
    print find_path(L, "ccc") # prints [0,1,1]
    print L[0][1][1] # prints ccc
    print get_node(L, find_path(L, "bbb")[:-1]) # prints ['bbb', 'ccc']

However, in your case, there are only 2 levels of nesting, so that simpler functions could probably be used.

great code!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.