Copying nested lists in Python

自闭症网瘾萝莉.ら 提交于 2019-11-26 00:25:54

问题


I want to copy a 2D list, so that if I modify one list, the other is not modified.

For a one-dimensional list, I just do this:

a = [1, 2]
b = a[:]

And now if I modify b, a is not modified.

But this doesn\'t work for a two-dimensional list:

a = [[1, 2],[3, 4]]
b = a[:]

If I modify b, a gets modified as well.

How do I fix this?


回答1:


For a more general solution that works regardless of the number of dimensions, use copy.deepcopy():

import copy
b = copy.deepcopy(a)



回答2:


b = [x[:] for x in a]



回答3:


you can also use this code without importing copy package

b=a.copy()


来源:https://stackoverflow.com/questions/2541865/copying-nested-lists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!