【问题标题】:How do I access the nth nested list, were I know the depth of nested lists?如何访问第 n 个嵌套列表,我是否知道嵌套列表的深度?
【发布时间】:2021-02-26 21:31:58
【问题描述】:

在一般情况下,我正在对嵌套循环深度可变的嵌套列表中的数据点进行分类,例如在一个简单的情况下:

alist = [ [[a, b], [c, d]],  [[e, f], [g, h]] ]

我用它来进行括号之类的操作,例如:

min ([ max([a, b]), max([c,d]) ])

但是我遇到的问题是,在我的示例中,我引用了 [a, b] 和 [c, d],但我想将它们引用为列表的变量或索引,以防我们已知深度嵌套列表和已知数量的最深嵌套括号中的元素。

根据我对使用列表索引的了解,我看不出如何在嵌套列表中引用 nth 深度。如果我想引用第三个嵌套列表,我必须明确写:

nlist[0][0][i]

因此,如果深度发生变化,我将无能为力。

【问题讨论】:

    标签: python tree nested-lists depth


    【解决方案1】:

    您需要了解的不仅仅是深度。就像在最后一个示例中一样,您需要有 3 个值:0、0、i。

    在一般情况下,您需要知道 n 个索引。

    因此,您可以编写一个将这些索引作为参数的小辅助函数:

    def deep_get(lst, *indices):
        for i in indices:
            lst = lst[i]
        return lst
    

    现在,当您拥有indices 列表时,您可以这样做:

    indices = [0, 0, i]
    # ...
    # ...
    print(deep_get(lst, *indices))
    

    设置

    如果你需要设置一个值而不是获取它,那么使用这个函数:

    def deep_set(lst, value, *indices):
        for i in indices[:-1]:
            lst = lst[i]
        lst[indices[-1]] = value
    

    调用为:

    indices = [0, 0, i]
    # ...
    # ...
    newValue = 9
    print(deep_set(lst, newValue, *indices))
    

    【讨论】:

    • 如果不是拉取或获取带有索引的列表,我想在索引处分配一个值,例如:indices = [0, 0, 1]
    • 查看补充答案。
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2021-10-20
    • 2012-09-20
    相关资源
    最近更新 更多