【发布时间】:2019-04-16 17:44:10
【问题描述】:
我有一些列表和值以任意深度相互嵌套。
nested = [
3,
[1, 4, 2],
[3, [5], 6, 7, [5]],
[3],
[[1, 1],[2, 2]]
]
我正在尝试在这个嵌套的混乱中设置一个值 使用任意长的索引。
示例索引:
index = (2, 1)
所以在示例索引处设置一个项目:
nested[2][1] = new_value
如果我们知道索引的长度,我们可以:
nested[index[0]][index[1]] = new_value
问题是索引不是设定的长度!
我想出了如何获取任意长度索引的值:
def nested_get(o, index):
if not index:
return o
return nested_get(o[index[0]], index[1:])
我知道 numpy 数组可以这样做:np_array[index] = new_value
我怎样才能实现一个函数来做类似的事情,但使用纯 python?类似于nested_get,但用于设置值。
【问题讨论】:
-
设置和获取一样,只需要多传一个参数。当你到达最后一个索引时,做作业。
标签: python python-3.x list nested