2016-07-17 8 views
-1

2つのネストされたforループと2つのリストがあります。内側のループの1回の反復の後にtleリストの1つを再初期化します。ダミーのコードは、私がnewiのクリーンな新しいインスタンスが内部ループの1回の繰り返しの後iのものになりたい ネストされたPython forループの変数スコープ

def test(): 
i = ['1','5','9','3','6','4'] 
for x in xrange(0,len(i)): 
    j = ['6', '7', '9', '3'] 
    newi = i 
    for y in xrange(0,len(j)): 
     newi[x] = j[y] 
     print "i", i 
    print "end of one iteration on finner loop" 
    print "newi", newi 
test() 

その

は、現在、それは内側のループの値を浮き袋

電流出力:

i ['6', '5', '9', '3', '6', '4'] 
i ['7', '5', '9', '3', '6', '4'] 
i ['9', '5', '9', '3', '6', '4'] 
i ['3', '5', '9', '3', '6', '4'] 
end of one iteration on inner loop 
newi ['3', '5', '9', '3', '6', '4'] 
i ['3', '6', '9', '3', '6', '4'] 
i ['3', '7', '9', '3', '6', '4'] 
i ['3', '9', '9', '3', '6', '4'] 
i ['3', '3', '9', '3', '6', '4'] 
end of one iteration on inner loop 
newi ['3', '3', '9', '3', '6', '4'] 
i ['3', '3', '6', '3', '6', '4'] 
i ['3', '3', '7', '3', '6', '4'] 
i ['3', '3', '9', '3', '6', '4'] 
i ['3', '3', '3', '3', '6', '4'] 
end of one iteration on inner loop 
newi ['3', '3', '3', '3', '6', '4'] 
i ['3', '3', '3', '6', '6', '4'] 
i ['3', '3', '3', '7', '6', '4'] 
i ['3', '3', '3', '9', '6', '4'] 
i ['3', '3', '3', '3', '6', '4'] 
end of one iteration on inner loop 
newi ['3', '3', '3', '3', '6', '4'] 
i ['3', '3', '3', '3', '6', '4'] 
i ['3', '3', '3', '3', '7', '4'] 
i ['3', '3', '3', '3', '9', '4'] 
i ['3', '3', '3', '3', '3', '4'] 
end of one iteration on inner loop 
newi ['3', '3', '3', '3', '3', '4'] 
i ['3', '3', '3', '3', '3', '6'] 
i ['3', '3', '3', '3', '3', '7'] 
i ['3', '3', '3', '3', '3', '9'] 
i ['3', '3', '3', '3', '3', '3'] 
end of one iteration on inner loop 
newi ['3', '3', '3', '3', '3', '3'] 

答えて

0

の代わりに:

newi = i 

repla ce:

newi = list(i) # list(i) creates another copy i 
関連する問題