2016-03-07 45 views
-1

我發現在執行for循環顯示可變項目列表時,我無法修改該項目,但是如果該元素是可變的,我可以修改該項目的元素。爲什麼?無法修改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 ! 

我知道修改你所迭代的名單是不是好的做法(這是更好地遍歷它的副本),所以請不要點我的那一刻。

+1

看一看此http: //stackoverflow.com/questions/2022031/python-append-vs-operator-on-lists-why-do-these-give-different-results。 – AKS

+0

@AKS謝謝,請看看它 –

回答

0

這樣的行爲的原因是,雖然用於環路#執行新列表是通過將操作者+列出產生(也可以通過獲取的xid跟蹤)。

但是在for循環#2通過項目的訪問元素與索引x[0]已在內存中的對象正在被修改。它可以通過調用X id很容易被發現,而迭代alist

# 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內進行循環修改項目,請參閱下面的示例:

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