分配给带有索引列表的嵌套列表

问题描述 投票:0回答:1

给定一个嵌套列表,您可以使用类似的方式访问元素

data = [[12, 15], [21, 22], [118, 546], [200, 1200]]

assert data[0][0] == 12

问题是,在这种情况下,我想用“索引列表”索引到嵌套列表中,并且在运行时长度是动态的。例如,上面的“索引列表”将是 [0,0]

我想要这种通用类型的功能

def nested_list_assignment(nested_list, list_of_indices, value):

并且会像这样工作

# passes this basic test
data = [[12, 15], [21, 22], [118, 546], [200, 1200]]

assert data[0][0] == 12
nested_list_assignment(data, [0, 0], 0)
assert data[0][0] == 0

我有一个类似的工作实现

def nested_list_assignment(nested_list, list_of_indices, value):
    # ill handle this case later
    assert len(list_of_indices) > 0

    if len(list_of_indices) == 1:
        nested_list[list_of_indices[0]] = value
    else:
        nested_list_assignment(nested_list[list_of_indices[0]], list_of_indices[1:], value)

但我很好奇Python是否为此提供了任何构造,或者只是为此提供了一个标准库函数。

python list variable-assignment nested-lists
1个回答
0
投票

没有标准的 Python 函数或运算符,但只要您确定被索引的所有内容本身都可以使用

indices
:

的元素进行索引,这样的东西通常就可以工作。
def list_assignment(xs, indices, x):
    for i in indices[:-1]:
        xs = xs[i]
    xs[indices[-1]] = x


data = [[12, 15], [21, 22], [118, 546], [200, 1200]]
list_assignment(data, [0, 0], 0)
print(data)

输出:

[[0, 15], [21, 22], [118, 546], [200, 1200]]

这适用于您可以索引的任何内容:

d = { 
    'a': {
        'b': 1,
        'c': 2,
    },
    'd': 3
}

list_assignment(d, ['a', 'c'], 42)
print(d)

输出:

{'a': {'b': 1, 'c': 42}, 'd': 3}
© www.soinside.com 2019 - 2024. All rights reserved.