[英]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']? 如何检索我发现的以['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. 我不知道“ S”嵌套的深度。
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 RuntimeError:超过最大递归深度
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
: 使用您的
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]
获取该列表:
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). 它首先使用键
(2, 1)
获取字典值,然后获取该值(这是一个列表)并在索引1处获取其项,这是列表中的第二项(在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): []
(顺便说一句,在你的例子中,你在
(1,2): []
之后错过了一个逗号(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. 我递归检查了“ S”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.