简体   繁体   English

为什么我更改复制的列表时原始列表会更改(PYTHON)

[英]Why does the original list change when I change the copied list (PYTHON)

So I have this simple code:所以我有这个简单的代码:

list = [[1,2],[4,5]]
list1 = list.copy() 
for i in range(len(list)):
    for j in range(len(list[i])):
        print(i,j, ":", list[i][j], "and", j,i, ":", list1[j][i])
        nr = input('Line {0}, Column{1}: ' .format(i+1, j+1) )
        list[i][j] = nr
        list1[j][i] = nr
        print(list,list1)
print(list1, list)

If I want the final result of the variable list to be the following matrix: [[1,2],[3,4]] , so the variable list1 should be the transposed matrix: [[1,3],[2,4]] .如果我希望变量列表的最终结果是以下矩阵: [[1,2],[3,4]] ,那么变量list1应该是转置矩阵: [[1,3],[2,4]] Somehow the result is this: [['1', '3'], ['3', '4']] [['1', '3'], ['3', '4']] .结果是这样的: [['1', '3'], ['3', '4']] [['1', '3'], ['3', '4']] Please someone help me.请有人帮助我。 Thanks and have a good weekend谢谢,周末愉快

you should use copy.deepcopy .你应该使用copy.deepcopy

If your list is a list of integers or floats, copy would suffice but since you have list of lists, you need to recursively copy the elements inside the lists.如果您的列表是整数或浮点数列表,则copy就足够了,但是由于您有列表列表,因此您需要递归地复制列表中的元素。

You can find more detailed answer here: What is the difference between shallow copy, deepcopy and normal assignment operation?你可以在这里找到更详细的答案: 浅拷贝、深拷贝和普通赋值操作有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的原始列表会更改? - Why does my original list change? 为什么当我更改另一个列表时列表会发生变化? - Why does a list change when i change another? Python:为什么我的原始列表在更新复制列表后会受到影响 - Python: why my original list is affected after updating copied list 任何人都可以告诉我为什么在复制列表中更新时我的原始列表会更新? - Anyone can tale me why my Original list updating when I Update in copied list? 为什么更改链表的复制版本会更改原始链表? - Why does changing the copied version of the linkedlist change the original linkedlist? 关于为什么某个 function 不改变原始列表的值(Python)的初学者问题? - Beginner question about why a certain function does not change the value of the original list (Python)? 当我更改链表中的指针时,原始指针是否仍然保留或自动删除? - When I change pointers in linked list, does the original still hold or does it get removed automatically? Python:为什么我的列表在我没有实际更改的情况下会更改? - Python: why does my list change when I'm not actually changing it? 为什么 function 不能正确更改 Python 中的列表 - Why a function does not change a list correctly in Python 为什么 python 会改变这个列表中的值? - Why does python change the value in this list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM