2015-02-08 67 views
-2

使用這個下面的例子:理解的Python的列表和字典使用的例子

對於世界上的每個人,我想創建自己的名單,我可以遍歷..

persons = [] 
attributes = {} 

for human in world: 
    attributes['name'] = human['name'] 
    attributes['eye_color'] = human['eyes'] 
    persons.append(attributes) 

現在,當我嘗試在我自己的列表中打印出每個名稱:

for item in persons: 
    print item['name'] 

他們都一樣,爲什麼?

回答

2

你是一遍又一遍地重複使用相同的字典persons.append(attributes)將該詞典的引用添加到列表中,它確實創建副本而不是

創建一個新的字典你的循環:

persons = [] 

for human in world: 
    attributes = {} 
    attributes['name'] = human['name'] 
    attributes['eye_color'] = human['eyes'] 
    persons.append(attributes) 

或者,使用dict.copy()創建字典的淺拷貝。

+0

我明白了,謝謝。 dict.copy()也非常有用,感謝鏈接。 – Prometheus 2015-02-08 13:20:32