-5
a=["a",["b",["c","d","e"],"f","g"],"h","j"]
b=a
index=[1,1,1]
for c in index:
  b=b[c]
print("Value: "+b.__str__())
#Code for change value to "k"
print(a)#result is ["a",["b",["c","k","e"],"f","g"],"h","j"]

在那里我可以获得价值,但我想把它换成另一个。

yourDict[1][1][1] = "测试"

不是这样的。索引必须来自数组。

4

1 回答 1

0
yourDict['b']['d']['b'] = "test"

编辑——OP提到这是不可接受的,因为索引必须来自运行时定义的任意长度的列表。

解决方案:

reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"

演示:

>>> yourDict = {'a':1, 'b':{'c':1, 'd': {'b':1}}}
>>> indexList = ['b','d','b']

>>> reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"
>>> yourDict
{'a': 1, 'b': {'c': 1, 'd': {'b': 'test'}}}

演示 2:

>>> yourDict = {'a':1, 'b':{'c':1, 'd': {'b':1}}}
>>> indexList=['a']

>>> reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"
>>> yourDict
{'a': 'test', 'b': {'c': 1, 'd': {'b': 1}}}
于 2012-08-14T19:22:32.837 回答