python将值分配给循环中的列表元素 [英] python assign values to list elements in loop

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

问题描述

这是有效的python行为吗?我认为最终结果应该是[0,0,0],并且id()函数每次迭代都应返回相同的值.如何使其成为pythonic,而不使用枚举或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实现的细节,不必是这种情况!)这就是为什么ID是将0分配给foo之后,也是如此.该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天全站免登陆