简体   繁体   中英

I have nested lists as entries to a Python dictionary. How do I print the nested list whose first elements is “S”?

I have a dictionary that looks like this:

my_dict = {(1,0): ['A', 'B'],
           (1,1): [[['E'], [['A', 'B'], ['C', 'D']]]],
           (1,2): [],
           (2,1): [[['E'], [['A', 'B'], ['C', 'F']]], [['S'], [[[['E'], [['A', 'B'], ['C', 'D']]]], [[['G'], [['H', 'J'], [[['E'], [['A', 'B'], ['C', 'F']]]]]]]]]]
           }

How do I retrieve the first sublist I find that begins with ['S']? For the example above I would like to get:

answer = [['S'], [[[['E'], [['A', 'B'], ['C', 'D']]]], [[['G'], [['H', 'J'], [[['E'], [['A', 'B'], ['C', 'F']]]]]]]]]

I don't know how deep the 'S' is nested.

EDIT:

I attempted to do it recursively as follows:

def recursive_check(longlist):
    for a_list in longlist:
        if 'S' in a_lis:
            return a_lis
        else:
            rec_check(a_list)

I received the following error:

RuntimeError: maximum recursion depth exceeded

EDIT: The list may look different and be nested differently every time.

def first_s(lst):
    if not (isinstance(lst, list) and lst):
        return None
    if lst[0] == ['S']:
        return lst
    else:
        for x in lst:
            y = first_s(x)
            if y:
                return y

Using your my_dict :

>>> print first_s(my_dict.values())
[['S'], [[[['E'], [['A', 'B'], ['C', 'D']]]], [[['G'], [['H', 'J'], [[['E'], [['A', 'B'], ['C', 'F']]]]]]]]]

To get that list: answer = my_dict[(2,1)][1]

It first gets the dictionary value with key of (2, 1) , then takes that value (which is a list) and gets its item at index 1, which is the second item in the list (after 0).

>>> my_dict = {(1,0): ['A', 'B'],
...            (1,1): [[['E'], [['A', 'B'], ['C', 'D']]]],
...            (1,2): [],
...            (2,1): [[['E'], [['A', 'B'], ['C', 'F']]], [['S'], [[[['E'], [['A', 'B'], ['C', 'D']]]], [[['G'], [['H', 'J'], [[['E'], [['A', 'B'], ['C', 'F']]]]]]]]]]
...            }
>>> my_dict[(2,1)][1]
 [['S'],
 [[[['E'], [['A', 'B'], ['C', 'D']]]],
 [[['G'], [['H', 'J'], [[['E'], [['A', 'B'], ['C', 'F']]]]]]]]]

(By the way, in your example, you are missing a comma after (1,2): []

...Update: which has now been fixed :) )

您可以打印像my_dict[(2,1)][1][0]这样的元素。

def nest(a,x):
    m=False
    for i in a: 
        if type(i)==list:
            m=nest(i,x)
        else:
            if i==x:
                return True
        return m


def our_fun(my_dict):
    for i in my_dict:
        for j in my_dict[i]:
            if nest(j,'S')==True:
                return my_dict[i]

I checked for 'S' recursively.

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