字典和列表之间的交互

时间:2019-03-26 14:28:11

标签: python list dictionary

这里是Python的新手,我注意到一种奇怪的行为,试图使用“新闻”之类的列表来记录字典更新

原始代码确实很复杂,因此我将其分解以重现不符合我期望的位

我有一个列表,它将被转换成字典

list2conv = ['Key1', 'Key2']

将其转换为字典

d_fromList = dict.fromkeys(list2conv)

for i in d_fromList:
    d_fromList[i] = [0, 0]

创建输出列表,这将是在字典中完成的一种操作日志,并添加一些值

outList = []

for i in range(0, 3):
    d_fromList['Key1'][0] = d_fromList['Key1'][0] + 10
    d_fromList['Key2'][1] = d_fromList['Key2'][1] + 20
    outList.append(d_fromList['Key1'])
    outList.append(d_fromList['Key2'])

实际结果

[[30, 0], [0, 60], [30, 0], [0, 60], [30, 0], [0, 60]] 

我会期望

[[10, 0], [0, 20], [20, 0], [0, 40], [30, 0], [0, 60]]

我在做什么错了?

2 个答案:

答案 0 :(得分:2)

您的代码有误:

    d_fromList['Key2'][1] = d_fromList['Key1'][1] + 20

应该是

    d_fromList['Key2'][1] = d_fromList['Key2'][1] + 20

答案 1 :(得分:1)

您遇到的现象称为别名。 当您开始使用嵌套列表/字典时,就会发生这种情况。 快速阅读: http://www.cs.rpi.edu/~sibel/csci1100/fall2015/course_notes/exam2_review/aliasing.html

一个快速解决方法是

for i in range(0, 3):
    d_fromList['Key1'][0] = d_fromList['Key1'][0] + 10
    d_fromList['Key2'][1] = d_fromList['Key2'][1] + 20
    outList.append(d_fromList['Key1'][:]) # copies the list
    outList.append(d_fromList['Key2'][:]) # copies the list
相关问题