简体   繁体   English

Python:如何将字典键的值附加在列表中而不是引用中?

[英]Python:how do you append the value of a dictionary key in a list and not the reference?

I have a dictionary consisting of names and a list in each key,like below: 我有一个字典,每个字典由名称和一个列表组成,如下所示:

dict1={}
for i in names:
    dict1[i]=[]

Then,I process a csv file and I find the result i need,I append it to the corresponding dictonary value,and I append in a list the name and the dictionary value,like below: 然后,我处理一个csv文件,找到需要的结果,将其附加到相应的字典值上,然后在列表中添加名称和字典值,如下所示:

list1=[]
for i2 in data:
    total_score=sum(i2[1:4])
    dict1[i2[0]].append(total_score)
    list1.append([i2[0],dict1[i2[0]]])

If i try to print the elements of the list1,I get the final list for each key,and not the progessive list. 如果我尝试打印list1的元素,则会得到每个键的最终列表,而不是渐进式列表。

The ending list should be like this: 结束列表应如下所示:

list1=[[name1,[50]],[name1,[50,60]],[name1,[50,60,0,85]]]

Any ideas?Thanks. 有什么想法吗?

Unless you will clone your list someway, there will be only one copy of it (in your words, the final one). 除非您以某种方式克隆您的列表,否则只有一个副本(用您的话说,就是最后一个)。 If I understand what you want, the solution is like 如果我了解您的需求,解决方案就像

list1=[]
for i2 in data:
    total_score=sum(i2[1:4])
    templist = dict1[i2[0]][:]
    templist.append(total_score)
    list1.append([i2[0],templist])

See http://docs.python.org/library/copy.html for more details. 有关更多详细信息,请参见http://docs.python.org/library/copy.html

Just change: 只是改变:

    list1.append([i2[0],dict1[i2[0]]]) 

to: 至:

    list1.append([i2[0],dict1[i2[0]][:]])

This will copy the current value of the list in dict1, instead of just referencing it. 这将在dict1中复制列表的当前值,而不仅仅是引用它。

(I'm guessing that this append used to be a print statement, which would just show the current value of the list in dict1. But when you save it into list1, you save a reference to the list, not a copy of it. The [:] slice operator makes a copy, so that additional appends to the list for key i2[0] won't be added to the copy.) (我猜想这个追加曾经是一个打印语句,它只会在dict1中显示列表的当前值。但是,当将其保存到list1中时,会保存对列表的引用,而不是副本。 [:] slice运算符进行复制,因此不会将密钥i2[0]的列表的其他追加添加到副本中。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM