python - 列表突然改变了,即使我没有改变它

标签 python python-3.x list deep-copy

我有相当复杂的代码。共有三个列表。简而言之 - list1 和比较列表应该进行比较,如果找到一些特定的匹配项,我们将 list1 中的值添加到 list2 中。整个代码如下

list1 = [['item1', ['item2'], '0', '0'], ['item3', ['item4'], '107', '2'], ['item4.5', ['item5', 'item4.5 aaa'], '120', '2'], ['item6', ['item6 item6 aaa'], '127', '1'], ['item7', ['item7 item7 aaa'], '129', '1']]
comparsion_list = [['item1', ['item2'], 'unknown'], ['item3', ['item4'], 'unknown'], ['item4.5', ['item5', 'item4.5 aaa'], 'unknown'], ['item6', ['item6 item6 aaa'], 'unknown']]
list2 = [['category', ['keywords'], ['long-names'], 'amount', 'amount2'],['empty', ['empty'], ['empty'], 'empty', 'empty']]

for a in range(len(comparsion_list)): #we go trough comparsion_list -start number is 1, end is category len
    for i in range(len(list1)): #and compare them with each item of list1

        if list1[i][1][0] in comparsion_list[a][1] and comparsion_list[a][2] not in [x[0] for x in list2]:
            list2.append([comparsion_list[a][2]]) #append item to list2 as list (to create row)
            list2[-1].append([list1[i][0]])
            list2[-1].append(list1[i][1])
            print("list1 before elif is: "+str(list1[0]))  #just for testing - everything still ok

        elif list1[i][1][0] in comparsion_list[a][1] and comparsion_list[a][2] == list2[-1][0]:
            print("list1 after elif is: "+str(list1[0])) #just for testing - not ok!
            list2[-1][2].extend(list1[i][1])

但输出如下:

list1 before elif is: ['item1', ['item2'], '0', '0']
list1 after elif is: ['item1', ['item2'], '0', '0']
list1 after elif is: ['item1', ['item2', 'item4'], '0', '0']
list1 after elif is: ['item1', ['item2', 'item4', 'item5', 'item4.5 aaa'], '0', '0']

如您所见,list1 已更改,但我没有在代码中全部更改!甚至没有引用,因为它始终是深层复制,并且 deep_of_list1 保持不变。我认为预期的输出应该是这样的:

list1 before elif is: ['item1', ['item2'], '0', '0']
list1 after elif is: ['item1', ['item2'], '0', '0']
list1 after elif is: ['item1', ['item2'], '0', '0']
list1 after elif is: ['item1', ['item2'], '0', '0']

但是当我删除这一行(从 elif 语句中):

    list2[-1][2].extend(list1[i][1])

然后输出就可以了(第二个)。 这怎么可能?我错过了什么?

最佳答案

您将对 list1 元素的引用附加到 list2。这些元素之一是可变的(list)本身。如果您通过显式复制列表来强制创建新的内存对象,您的问题就解决了。

list2[-1].append(list1[i][1].copy()) #in the 'if' part of the code.

除此之外,我可能会重构整个怪物..

关于python - 列表突然改变了,即使我没有改变它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49773027/

相关文章:

python - 将元组的字符串转换为元组

python sort itemgetter等效于N维嵌套列表

python - 将变量分配给具有相同键的字典项

python - 根据文件名的一部分合并文件

python-3.x - 逐 block 迭代加载图像,其中 block 部分重叠

python-3.x - 使用变量定义的 f 字符串

python - MongoAlchemy 中的复杂字符串查询

python - 图像进入空白图像中心的时刻(Python、OpenCV)

python - 带回调的 PyBindGen

java - 点击 RecyclerView 中的项目时日志中出现 "ViewPostImeInputStage processPointer 0"?