Python 使用for循环更新容器对象的结果

Python 使用for循环更新容器对象的结果,python,function,for-loop,Python,Function,For Loop,我正在学习Python。假设您有下面的函数返回新的dict'd',但它返回的是原始的未更改的dict。有人有正确的代码吗?(或者范围有问题吗??) 这是我创建的一个类似函数 >>> 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 >

我正在学习Python。假设您有下面的函数返回新的dict'd',但它返回的是原始的未更改的dict。有人有正确的代码吗?(或者范围有问题吗??)

这是我创建的一个类似函数

>>> 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]
>>>

谢谢!

正如@PaulPanzer告诉您的,这里的问题是
j
反弹到一个新的值,而不是dict中的值。根据需要更新dict中的值的代码如下:

def ask():
d = {'b': 7, 'c': 3, 'a': 2}
for i, j in d.items():    
    ans = int(input('the number for %s' %i))
    d[i] *= ans 
print(d.values())
这里,更新的值是dict中的值


我希望这能帮助你

因为您的
j
是一个整数,所以在Python中它是一个所谓的不可变对象。这意味着您的就地分配实际上并没有就地进行。相反,
j
会反弹到新值。因此对你的字典没有副作用。那么我需要“非本地”的东西吗?IDK how。您需要显式地为dict分配:
d[i]*=ans
def ask():
d = {'b': 7, 'c': 3, 'a': 2}
for i, j in d.items():    
    ans = int(input('the number for %s' %i))
    d[i] *= ans 
print(d.values())