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] =“测试”
不喜欢这样。索引必须来自数组。
答案 0 :(得分: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}}}