无法修改for循环中的列表项

时间:2016-03-07 03:36:27

标签: python for-loop

我发现在执行for循环可变项目列表时我无法修改该项目,但是如果该元素是可变的,我可以修改该项目的元素。为什么呢?

# Create alist which contain mutable
alist = [[1, 2, 3],]

#1 For loop
for x in alist:
    x = x + [9,]
print alist
# let's replace alist[0] to list which contain another one and try to modify it
alist[0] = [[[1,2],3]]

print2 alist # [[[[1, 2], 3]]]
#2 For loop
for x in alist:
    x[0] = x[0] + [9,]
# list modified ...
print alist # [[[[1, 2], 3, 9]]], Modified !

我知道修改你正在迭代的列表并不是一个好习惯(迭代它的副本更好),所以请不要指出我那个时刻。 / p>

1 个答案:

答案 0 :(得分:0)

此类行为的原因是,在执行 for循环#1 时,通过将+运算符应用于列表来生成新列表(可以通过获取id来跟踪它x)。

然而,在 for for循环#2 中,通过索引x[0]的项目的访问元素正在修改内存中的对象。在迭代alist

时,可以通过在x上调用id来轻松找到它
# Create alist which contain mutable
alist = [[1, 2, 3],]

#1 for loop
for x in alist:
    print id(x), id(alist[0]), 'Same?:', id(x) == id(alist[0]) 
    # id(x): 4425690360 id(alist[0]) 4425690360 Same?: True
    x = x + [9,]
    print id(x), id(alist[0]), 'Same?:', id(x) == id(alist[0]) 
    # id(x): 4425770696 id(alist[0]) 4425690360 Same?: False
# mutable item not modified, so my guess is that x actually are copy of that item
print alist # [[1, 2, 3]]
# let's replace alist[0] to list which contain another one and try to modify it
alist[0] = [[[1,2],3]]

print alist
#2 for loop
for x in alist:
    print id(x), id(alist[0]), 'Same?:', id(x) == id(alist[0]) 
    # id(x): 4425811008 id(alist[0]) 4425811008 Same?: True

    x[0] = x[0] + [9,]
    print id(x), id(alist[0]), 'Same?:', id(x) == id(alist[0])
    # id(x): 4425811008 id(alist[0]) 4425811008 Same?: True
# list modified ...
print alist # [[[[1, 2], 3, 9]]]

要解决问题,请使用array.append修改for循环中的项目,请参阅下面的示例:

alist = [[1, 2, 3],]
for x in alist:
    print id(x), id(alist[0]), 'Same?:', id(x) == id(alist[0])
    x.append(9)
    print id(x), id(alist[0]), 'Same?:', id(x) == id(alist[0])
# list modified ...
print alist # [[1, 2, 3, 9],]