2012-08-14 40 views
-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"] 

在那裏我可以獲取值,但我想將其更改爲另一個值。Python從數組索引中更改數組的值

yourDict [1] [1] [1] = 「測試」

不是這樣。索引必須來自數組。

+1

這不是陣列。 – 2012-08-14 18:59:28

+1

[將任意長度位置\ [4,1,2 \]的列表轉換爲嵌套列表的索引的可能的重複](http://stackoverflow.com/questions/6558365/convert-list-of-positions- 4-1-2任意長度的索引爲嵌套) – 2012-08-14 19:00:55

+0

請在提問前閱讀常見問題解答。 – devsnd 2012-08-14 19:03:15

回答

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}}} 
+0

@TalhaZekeriyaDurmuş:你應該在你的問題中提到,然後編輯它。 – ninjagecko 2012-08-14 19:40:54

+0

非常感謝。你是救生員 – 2012-08-14 19:49:20