我有一些列表和值以任意深度相互嵌套。
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
但用于设置值。
最佳答案
你可以用递归函数做一些事情:
def nested_set(x, index, value):
if isinstance(index, int):
x[index] = value
return
elif len(index) == 1:
x[index[0]] = value
return
nested_set(x[index[0]], index[1:], value)
很可能有一些比列表更好的数据结构可以满足您的需求。
关于python - 使用任意长度索引设置嵌套列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713873/