0

is it possible to search a multi dimensional list for a certain letter then print out where that letter is?
i know u can use list.index() to find a letter but i could figure out how to do it with multi dimensional lists.

thx in advance

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by pythopian
0

is it possible to search a multi dimensional list for a certain letter then print out where that letter is?
i know u can use list.index() to find a letter but i could figure out how to do it with multi dimensional lists.

thx in advance

Something like this perhaps:

for idx_i, each_sublist in enumerate(main_object):
    for idx_j, each_string in enumerate(each_sublist):
        if each_string == my_letter:
            print 'Found %s at %s, %s' % (my_letter, idx_i, idx_j)

That could possibly work for you, otherwise you'll need to be a little more clear. Example input/output would help to define a way to solve this

1

If you want to search sequences with more than 2 levels of nesting, you could do this:

def deepfind(obj, test=lambda value: True):
    if not isinstance(obj, (list, tuple)):
        if test(obj):
            yield obj
    else:
        for each in obj:
            for found in deepfind(each, test):
                yield found

def test():
    data = [
        ['abc', 'def', 'geh'], [
            ['ijk', 'lmn', 'opq'],
            ['rst', 'uvw', 'xyz'],
            ],
        ]
    print list( deepfind(data, lambda value: 'a' in value or 'z' in value) )

>>> test()
['abc', 'xyz']
This article 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.