0
我正在學習Python。假設你有下面的函數返回新的字典'd',但它返回原來不變的字典。有沒有人有這個正確的代碼? (或者是有毛病範圍???)使用for循環來更新容器對象的結果
>>> def ask():
... d = {'b': 7, 'c': 3, 'a': 2}
... for i, j in d.items():
...
... ans = int(input('the number for %s' %i))
...
... j *= ans
...
... print(d.values())
...
>>> ask()
the number for b3
the number for c235
the number for a432
dict_values([7, 3, 2])
這裏是我創建了一個類似的功能...
>>> def ask_for_input():
d = [1,2,3,4,5,6,7]
for i in d:
ans = int(input('The number for %i' %i))
i *= ans
return d
>>> print(ask_for_input())
The number for 15
The number for 27
The number for 35345
The number for 474
The number for 53
The number for 6788
The number for 754
[1, 2, 3, 4, 5, 6, 7]
>>>
謝謝!
既然你的'j'是一個整數,它就是Python中所謂的不可變對象。這意味着你的就地分配並不是真正發生的。相反'j'會反彈到新值。因此,你的字典沒有副作用。 –
那麼我需要'非本地'的東西? IDK如何。 – Roy
您需要明確指定您的字典:'d [i] * = ans' –