如果a = list和b = a,如何确保循环仅影响b而不会影响a?

时间:2019-04-05 16:39:18

标签: python

(python)我正在尝试创建一个单独的列表,以根据现有列表中的条件存储和修改元素。我希望修改新列表(b),而不要修改原始列表(a)。为什么我的代码同时影响a和b以及如何解决?

a=[[0,0,0,1,0],[1,1,3,0,0],[0,0,3,0,0],[0,0,3,1,1],[0,0,0,0,0]]
b=a 
#b is the new list that i want to modify

for i in range(0,len(a)):
```for j in range(0,len(a[i])):
   ```if a[i][j]==3:
      ````b[i][j]=2

print(b)
print(a)



Expected
[[0, 0, 0, 1, 0], [1, 1, 2, 0, 0], [0, 0, 2, 0, 0], [0, 0, 2, 1, 1], [0, 0, 0, 0, 0]] 
#this is b

[[0, 0, 0, 1, 0], [1, 1, 3, 0, 0], [0, 0, 3, 0, 0], [0, 0, 3, 1, 1], [0, 0, 0, 0, 0]]
#this is a

Actual
[[0, 0, 0, 1, 0], [1, 1, 2, 0, 0], [0, 0, 2, 0, 0], [0, 0, 2, 1, 1], [0, 0, 0, 0, 0]] 
#this is b

[[0, 0, 0, 1, 0], [1, 1, 2, 0, 0], [0, 0, 2, 0, 0], [0, 0, 2, 1, 1], [0, 0, 0, 0, 0]]
#this is a

a should not be modified but it is.

0 个答案:

没有答案