简体   繁体   English

如何在python中的for循环中更改列表元素的值?

[英]How do i change a list element's value in a for loop in python?

I am having a bit of trouble changing the values of list elements when utilizing a for loop. 使用for循环时,更改列表元素的值时遇到麻烦。 The following code outputs 10 and 5 - but I'm expecting 10 and 10. 以下代码输出10和5-但我期望10和10。

amount = 5
costFieldList = [amount]

for index, field in enumerate(costFieldList):
    if type(field) is int:
        costFieldList[index] = field*2
        print(costFieldList[index])
print(amount)

Is this an issue of scope? 这是范围问题吗? Thanks in advance. 提前致谢。

You are printing amount at the end. 您正在最后打印amount This is set to an immutable value (5). 将其设置为不变值(5)。

If your last line is print(costFieldList) , you will see that it is [10] as expected. 如果最后一行是print(costFieldList) ,则会看到它是预期的[10] You used amount to initialize the list, but there is no link back to modify amount. 您使用了数量来初始化列表,但是没有链接可以修改数量。

By writing costFieldList[index] = field*2 , you are creating an entirely new int instance which then overwrites the "reference" to the instance in the array, but not the value itself. 通过写入costFieldList[index] = field*2 ,您将创建一个全新的int实例,该实例然后覆盖对数组中实例的“引用”,但不覆盖值本身。 So you lose the reference to the original value of amount . 所以,你就失去了参考的原始值amount

At this stage amount still has a "reference" to 5 which is why you get 5 as the second output. 在此阶段, amount仍然有对5的“引用”,这就是为什么您将5作为第二个输出。

If you want to set both amount and costFieldList[index] to field * 2 use: 如果要将“ amount和“ costFieldList[index]field * 2使用:

amount = 5
costFieldList = [amount]

for index, field in enumerate(costFieldList):
    if isinstance(field,int):  # use issinstance to check if field is an integer
        costFieldList[index] = field * 2
        print(costFieldList)
        amount=costFieldList[index] # set amount to value of costFieldList index 
print(amount,costFieldList ) 
(10, [10])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM