2017-01-18 4 views
0

リストはオブジェクトなので、この動作はリファレンスが追加されているために必要です。 これはどのように正確に動作し、これを行う正しい方法は何ですか?1Dリストを2Dリストに追加して後で修正すると、前のエントリも変更されます

コード(発見されたインデックス位置をインクリメントする):

# generating labels for debugging 
#labels = [3]*3 + [1]*3 + [4]*2 
labels = [3, 3, 3, 1, 1, 1, 4, 4] 
print "labels list is", labels 

counter_table = [] 
#counter = [0]*6 
counter = [0 for i in range(6)] 
for i in labels: 
    curr_label = i 
    counter[curr_label] = counter[curr_label] + 1 
    print "current counter list is", counter 
    counter_table.append(counter) 
print "final counter_table is", counter_table 

出力:

labels list is [3, 3, 3, 1, 1, 1, 4, 4] 
current counter list is [0, 0, 0, 1, 0, 0] 
current counter list is [0, 0, 0, 2, 0, 0] 
current counter list is [0, 0, 0, 3, 0, 0] 
current counter list is [0, 1, 0, 3, 0, 0] 
current counter list is [0, 2, 0, 3, 0, 0] 
current counter list is [0, 3, 0, 3, 0, 0] 
current counter list is [0, 3, 0, 3, 1, 0] 
current counter list is [0, 3, 0, 3, 2, 0] 
final counter_table is [[0, 3, 0, 3, 2, 0], [0, 3, 0, 3, 2, 0], [0, 3, 0, 3, 2, 0], [0, 3, 0, 3, 2, 0], [0, 3, 0, 3, 2, 0], [0, 3, 0, 3, 2, 0], [0, 3, 0, 3, 2, 0], [0, 3, 0, 3, 2, 0]] 
+0

はループ内で 'counter'を再初期化します。変更を積み重ね、すべての "フレーム"を取得しない限り、コピーを作成する必要があります。 –

+0

これは正確に何が起こっているか、毎回同じリスト参照を追加しています。この問題の可能な解決策については、http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-listを参照してください。 – jarandaf

+0

この記事は役に立ちましたか:SOベテランのNed Batchelderによって書かれた[Pythonの名前と値についての事実と神話](http://nedbatchelder.com/text/names.html) –

答えて

2

あなたは何のメモリをキープしたいものはおそらくですcounterの参照を、再利用していますハプニング。

だから別に

counter = [0]*6 
for curr_label in labels: 
    counter[curr_label] += 1 
    print "current counter list is", counter 
    counter_table.append(counter[:]) # create a copy 

あなたのリストのコピーを保存:私はあなたがcounter = [0]*6を使用するには消極的だったことを見た:それは完全に(不変オブジェクトのリストに同じを使用しての危険性を*を使用しないためにすべての権利ですそうでない場合はに変更を

counter_table.append(list(counter)) 

:その場合の基準)

+0

ありがとう!これだよ! – devautor

0

あなたは、リストのコピーを生成する必要がありますはcounter_table内のすべての出現を変更します。

関連する問題