给定嵌套列表元素,找到一级返回列表值

时间:2019-03-22 08:23:23

标签: python list indexing nested

说我有 List=[[[['a','b'],['c','d'],['e','f']],[['1','2'],['3','4'],['5','6']]],[[['a','b'],['c','d'],['e','f']],[['1','2'],['3','4'],['5','6']]]] 我知道如果我打电话给List[0][0],我会得到[['a', 'b'], ['c', 'd'], ['e', 'f']],依此类推。

是否存在任何内置或外部python函数(假设其func(a))或使嵌套列表元素a返回一级的方法?

因此,如果我调用func(List[0][1]),这些函数将返回List[0],或者当我调用func(List[1][0][1])时,这些函数将返回List[1][0],但是如果我调用func(List),它将返回返回List,因为它已经在根目录了。我已经在寻找这种问题好几个小时了,但仍然找不到解决方法。

1 个答案:

答案 0 :(得分:0)

您可以使用以下递归函数:

def get_parent_list(the_elem, the_list):
    if (the_elem == the_list):
        return (True, the_elem)
    elif the_elem in the_list:
        return (True, the_list)
    else:
        for e in the_list:
            if (type(e) is list):
                (is_found, the_parent) = get_parent_list(the_elem, e)
                if (is_found):
                    return (True, the_parent)
        return (False, None)

进行测试:

my_list=[[[['a','b'],['c','d'],['e','f']],[['1','2'],['3','4'],['5','6']]],
         [[['a','b'],['c','d'],['e','f']],[['1','2'],['3','4'],['5','6']]]]

测试案例1:

the_child = my_list[0][1][1]
the_flag, the_parent = get_parent_list(the_child, my_list)
print (the_flag)
print (the_child)
print (the_parent)

结果:

True
['3', '4']
[['1', '2'], ['3', '4'], ['5', '6']]

测试案例2:

the_child = my_list[0][1]
the_flag, the_parent = get_parent_list(the_child, my_list)
print (the_flag)
print (the_child)
print (the_parent)

结果:

True
[['1', '2'], ['3', '4'], ['5', '6']]
[[['a', 'b'], ['c', 'd'], ['e', 'f']], [['1', '2'], ['3', '4'], ['5', '6']]]

测试案例3:

the_child = my_list[:]
the_flag, the_parent = get_parent_list(the_child, my_list)
print (the_flag)
print (the_child)
print (the_parent)

结果:

True
[[[['a', 'b'], ['c', 'd'], ['e', 'f']], [['1', '2'], ['3', '4'], ['5', '6']]], [[['a', 'b'], ['c', 'd'], ['e', 'f']], [['1', '2'], ['3', '4'], ['5', '6']]]]
[[[['a', 'b'], ['c', 'd'], ['e', 'f']], [['1', '2'], ['3', '4'], ['5', '6']]], [[['a', 'b'], ['c', 'd'], ['e', 'f']], [['1', '2'], ['3', '4'], ['5', '6']]]]

测试案例4:

the_child = my_list[0][1] + ['Non-existent value']
the_flag, the_parent = get_parent_list(the_child, my_list)
print (the_flag)
print (the_child)
print (the_parent)

结果:

False
[['1', '2'], ['3', '4'], ['5', '6'], 'Non-existent value']
None