Python list.append函数意外更改了先前添加的成员

时间:2018-09-12 09:46:34

标签: python-2.7 list

我正面临python的问题,如下所示:

  • 我有2个初始列表:

first_list = [['a1','a2'],['a1','a2']]

second_list = ['b1','b2']

  • 我想用另一个列表中的每个值替换second_list中的“ b2”,然后将其添加到first_list中。例如:

parts = ['C','D']

我对first_list的预期结果将是:[['a1','a2'],['a1','a2'],['b1','C'],['b1','D' ]]

这是我的代码:

first_list = [['a1','a2'], ['a1','a2']]
second_list = ['b1','b2']

parts = ['C', 'D']

for record in parts:
    print record    #print to see which value we will use to replace "b2"
    temp = second_list
    temp[1] = record
    print temp      #print to see which value will be appended to first_list
    first_list.append(temp)
    print first_list     #print first_list after adding a new member

结果是:

C
['b1', 'C']
[['a1', 'a2'], ['a1', 'a2'], ['b1', 'C']]
D
['b1', 'D']
[['a1', 'a2'], ['a1', 'a2'], ['b1', 'D'], ['b1', 'D']]

我怀疑有什么问题,但无法解释。用“插入”功能代替“添加”仍然显示相同的问题。有人可以帮我吗?

谢谢

2 个答案:

答案 0 :(得分:1)

问题是您在此步骤temp = second_list

中仅复制了参考

所以temp实际上和second_list一样

您必须复制可以执行的值,例如像这样temp = second_list[:],它将创建新列表并且应该可以工作

答案 1 :(得分:1)

每次您都更新相同的列表(temp)。
要获得预期的行为,您需要做的就是维护列表的新副本。

for record in parts:
    print record    #print to see which value we will use to replace "b2"
    temp = second_list[:]  #make a new copy
    temp[1] = record
    print temp      #print to see which value will be appended to first_list
    first_list.append(temp)
    print first_list     #print first_list after adding a new member