Python 使用任意长度索引设置嵌套列表中的元素

Python 使用任意长度索引设置嵌套列表中的元素,python,python-3.x,list,nested,Python,Python 3.x,List,Nested,我有一些列表和值以任意深度相互嵌套 nested = [ 3, [1, 4, 2], [3, [5], 6, 7, [5]], [3], [[1, 1],[2, 2]] ] 我试图在这个嵌套的混乱中设置一个值 使用任意长的索引 示例索引: index = (2, 1) nested[2][1] = new_value 因此,在示例索引处设置一个项目: index = (2, 1) nested[2][1] = new_value 如果我们知道索引

我有一些列表和值以任意深度相互嵌套

nested = [
    3,
    [1, 4, 2],
    [3, [5], 6, 7, [5]],
    [3],
    [[1, 1],[2, 2]]
]
我试图在这个嵌套的混乱中设置一个值 使用任意长的索引

示例索引:

index = (2, 1)
nested[2][1] = new_value
因此,在示例索引处设置一个项目:

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\u数组[index]=new\u值


我如何用纯python实现这样的函数?类似于嵌套的\u 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)

可能有比列表更好的数据结构来完成您想要的任务。

设置与获取相同,您只需要传递一个额外的参数。当您到达最后一个索引时,执行赋值。@Hadus可能会让您感到困惑的是,getter使用空数组作为基本大小写,但您需要在设置时使用
len==1
作为基本大小写,因此,您有最后一个要分配给的列表。@user2653663我甚至没有使用列表,而是使用pytorch模块:),因此需要对所有使用的模块进行子类化,以包含更好的索引,但这是一个错误sufficient@Barmar我没有想到使用索引和一个更高的列表来简单地索引到它。我忘了。