我正面临python的问题,如下所示:
first_list = [['a1','a2'],['a1','a2']]
second_list = ['b1','b2']
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']]
我怀疑有什么问题,但无法解释。用“插入”功能代替“添加”仍然显示相同的问题。有人可以帮我吗?
谢谢
答案 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