给定的嵌套列表元素,找到一个级别的后列表值



说我有 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,因为它已经在根上。我一直在寻找这种问题已有几个小时了,但仍然找不到解决方案。

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

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

最新更新