python为循环中的列表元素赋值 [英] python assign values to list elements in loop

查看:148
本文介绍了python为循环中的列表元素赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有效的 python 行为吗?我认为最终结果应该是 [0,0,0] 并且 id() 函数应该在每次迭代中返回相同的值.如何使它成为 pythonic,而不使用 enumerate 或 range(len(bar))?

Is this a valid python behavior? I would think that the end result should be [0,0,0] and the id() function should return identical values each iteration. How to make it pythonic, and not use enumerate or range(len(bar))?

bar = [1,2,3]
print bar
for foo in bar:
    print id (foo)
    foo=0
    print id(foo)
print bar

输出:

[1, 2, 3]
5169664
5169676
5169652
5169676
5169640
5169676
[1, 2, 3]

推荐答案

首先,你不能重新分配循环变量——好吧,你可以,但这不会改变你正在迭代的列表.所以设置 foo = 0 不会改变列表,只会改变局部变量 foo(它恰好包含每次迭代开始时的迭代值).

First of all, you cannot reassign a loop variable—well, you can, but that won’t change the list you are iterating over. So setting foo = 0 will not change the list, but only the local variable foo (which happens to contain the value for the iteration at the begin of each iteration).

接下来,像 01 这样的小数被内部保存在一个小整数对象池中(这是一个 CPython 实现细节,不必就是这样!)这就是为什么在您将 0 分配给 foo 之后 ID 是相同的.id 基本上是池中那个整数对象 0 的 id.

Next thing, small numbers, like 0 and 1 are internally kept in a pool of small integer objects (This is a CPython implementation detail, doesn’t have to be the case!) That’s why the ID is the same for foo after you assign 0 to it. The id is basically the id of that integer object 0 in the pool.

如果你想在迭代时改变你的列表,不幸的是你必须通过索引访问元素.因此,如果您想保持输出相同,但最后有 [0, 0, 0],则必须遍历索引:

If you want to change your list while iterating over it, you will unfortunately have to access the elements by index. So if you want to keep the output the same, but have [0, 0, 0] at the end, you will have to iterate over the indexes:

for i in range(len(bar)):
    print id(bar[i])
    bar[i] = 0
    print id(bar[i])
print bar

否则,这是不可能的,因为一旦您将列表的元素存储在变量中,您就会有一个单独的引用,该引用与存储在列表中的元素无关.由于这些对象中的大多数都是不可变的,并且您在为变量分配新值时创建了一个新对象,因此您不会获得要更新的列表引用.

Otherwise, it’s not really possible, because as soon as you store a list’s element in a variable, you have a separate reference to it that is unlinked to the one stored in the list. And as most of those objects are immutable and you create a new object when assigning a new value to a variable, you won’t get the list’s reference to update.

这篇关于python为循环中的列表元素赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆