Copying nested lists in Python
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?
对于一个更通用的解决方案,无论维数如何,都可以使用copy.deepcopy()
:
import copy
b = copy.deepcopy(a)
b = [x[:] for x in a]
链接地址: http://www.djcxy.com/p/26698.html
上一篇: Polymer 1.0的tokenList样式发生了什么变化
下一篇: 在Python中复制嵌套列表