Python 使用其他列表中的索引更改列表中变量的值

Python 使用其他列表中的索引更改列表中变量的值,python,list,Python,List,我需要创建一个函数,该函数接受一系列整数、索引,具有任意长度,将用作嵌套列表、_列表的索引,并使用新值new_val更新最终索引处的值。例如: >>> the_list = [[1, 2], [3, 4], [5, 6]] >>> indices = [2, 1] >>> new_val = 'a' >>> foo(the_list, indices, new_val) [[1, 2], [3, 4],[5, 'a']]

我需要创建一个函数,该函数接受一系列整数、索引,具有任意长度,将用作嵌套列表、_列表的索引,并使用新值new_val更新最终索引处的值。例如:

>>> the_list = [[1, 2], [3, 4], [5, 6]]
>>> indices = [2, 1]
>>> new_val = 'a'
>>> foo(the_list, indices, new_val)
[[1, 2], [3, 4],[5, 'a']]
这相当于执行_list[index[0]][index[1]]=new_val,但我需要能够为任何长度的列表执行此操作


如果列表索引的长度为5,且列表仅为2,则函数仅使用索引中的前两个元素。

必须为列表的索引指定整数,因此这里的唯一解决方案是:

a[indices[0],indices[1]] = 11

正如你在编辑中提到的,你不知道索引。在这种情况下:

def get_ind(a,ind):
    if len(ind)==1:
        return a[0]
    return get_ind(a[ind[0]],ind[1:])
一些例子:

>>>a = [[["a", 15], [12, 0]], [[12, 4]]]
>>>indeces = [0,1,0]
>>>get_ind(a,indeces)
12
>>>a = [12, 4]
>>>indeces = [2]
>>>get_ind(a,indeces)
12
您还可以使用python来设置/获取值:

>>>a = [[["a", 15], [12, 0]], [[12, 4]]]
>>>indeces = [0,1,0]
>>>newval = 217
>>>s = "a"+"".join(['['+str(x)+']'for x in indeces])+"="+str(newval )
>>>s
'a[0][1][0]=217'
>>>exec s
>>>a
[[["a", 15], [217, 0]], [[12, 4]]]

你怎么决定是11号?规则是什么?索引与什么有什么关系?a[index[0]][index[1]]=11不起作用吗?人们是如何回答这个问题的?“这非常不清楚。”马龙猜测道intent@Trotom如果这是你的意思,请随意接受对不起,先生,但这不是我的意思。然而,我编辑并展示了更好的示例,所以也许现在您可以回答了?@Trotom我阅读了您的编辑并对其进行了更改。是否有任何方法可以更改元素的值而不是获取其值?@Trotom是的,我编辑了我的答案。这就是你要找的吗?