【问题标题】:Given nested list element, find the one level back list value给定嵌套列表元素,找到一级返回列表值
【发布时间】:2019-08-13 04:46:25
【问题描述】:

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

【问题讨论】:

  • 总而言之,如果您将列表视为一棵树,您想要一个函数,在给定子树的情况下,返回该子树的父节点?如果是这样,答案是否定的(至少在列表中)。但是,有许多树实现。
  • 是的,我想回到该列表的父节点。那么在python中真的没有其他方法可以得到这个吗?
  • 底线是,列表对于“构建”那种逻辑/抽象来说是一个不错的结构,但列表本身就是这种逻辑/结构的实现。您将不得不使用不同的结构或构建自己的结构。一旦你理解了这一点,你就可以开始寻找更好的替代方案来“存储/表示”这种关系。无论是图表、某种类型的字典/树结构,等等。
  • @Fauzi 实际上,列表不适合获取“父级”,因为创建列表时并没有考虑到特定的用例(显然)。这就是为什么你需要“更多”的东西。您可以选择树,也可以实现自己的结构(当然,两者都可以基于列表)。
  • 原来如此 :( 谢谢大家指出列表不能被视为像节点逻辑那样的父子节点。

标签: python list indexing nested


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2020-10-14
    相关资源
    最近更新 更多