在 Python 中复制嵌套列表 [英] Copying nested lists in Python

查看:19
本文介绍了在 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[:]

现在如果我修改 ba 不会被修改.

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[:]

如果我修改 ba 也会被修改.

If I modify b, a gets modified as well.

我该如何解决这个问题?

How do I fix this?

推荐答案

要获得更通用的解决方案,无论维数如何,都可以使用 copy.deepcopy():

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

import copy
b = copy.deepcopy(a)

这篇关于在 Python 中复制嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆