Python更新列表会影响其他列表

时间:2017-07-28 14:27:32

标签: python list python-3.5

如果在其他地方得到回答,请道歉。我已经搜索了堆栈溢出但找不到这个问题的答案。

我不明白为什么即使在创建临时列表并将新行放入其中并将其分配给列表L2之后,列表L1也会被修改。

据我所知,我没有复制temp_list旁边的任何列表,因此内存中没有链接列出L1。

谢谢你

>>> L1 = []
>>> a = ['this','is','a','test','message']
>>> L1.append(a)
>>> b = ['this','is','another','good','message']
>>> L1.append(b)
>>> print (L1)
[['this', 'is', 'a', 'test', 'message'], ['this', 'is', 'another', 'good', 
'message']]
>>> list_copy_L1 = L1[:]
>>> L2 = []
>>> temp_list = []
>>> for row in list_copy_L1:
        if row[3] == 'good':
            row[3] = 'BAD'
        temp_list.append(row)
>>> L2 = temp_list[:]
>>> print (L1)
[['this', 'is', 'a', 'test', 'message'], ['this', 'is', 'another', 'BAD', 
'message']]
>>> print (L2)
[['this', 'is', 'a', 'test', 'message'], ['this', 'is', 'another', 'BAD', 
'message']]
>>> 

0 个答案:

没有答案