看板 Python 關於我們 聯絡資訊
a={} addr = [1,2,3,4] children=[5,6,7,8] h="!" for x in addr: a[x]=children a[x].append(h) print a ========================================================== 執行結果 {1: [5, 6, 7, 8, '!', '!', '!', '!'], 2: [5, 6, 7, 8, '!', '!', '!', '!'], 3: [5, 6, 7, 8, '!', '!', '!', '!'], 4: [5, 6, 7, 8, '!', '!', '!', '!'] } 請問為什麼會有[5,6,7,8]後面會有4個"!"而不是只有1個? 如果我只要1個應該怎麼改呢? 謝謝 -- A:妳是琪汀嗎? B:不...我是喜瑞兒絲。 ------------------------------------------------------------------------------- A:Are you kidding? B:No, I'm serious. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.118.122.92 ※ 編輯: CHRyo 來自: 140.118.122.92 (06/29 13:22)
holio:因為 a[x]=children 不是複製 所以 a[x].append(h) 其實是 06/29 13:34
holio:append 在 children 06/29 13:34
subook:要複製新的一份可用 a[x]=list(children) 06/29 13:39
CHRyo:感謝樓上兩位 06/29 13:52