在python中复制列表 [英] copy a list in python

查看:50
本文介绍了在python中复制列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请在python中这两个代码有什么区别?

Please what's the difference between this two codes in python:

white=[2,4,8,9]
black = white

white=[2,4,8,9]
black = white[:]

非常感谢您.

推荐答案

第一个将对列表 white 的引用复制到变量 black

The first copies a reference to the list white to the variable black

因此,对黑色的任何更改也会更改 white ,反之亦然

So any changes to black will also alter white and visa versa

将其视为 white

第二个将列表 white 的内容复制到变量 black ,也许这样写更好

The second copies the contents of the list white to the variable black and is perhaps better written like this

black = list(white)

在这种情况下,两个变量 black white 之间没有连接,因为复制的是 white 的内容,而不是对 white 本身的引用.

In this case there is no connection between the two variables black and white as it is the contents of white that are copied and not a reference to white itself.

请额外考虑以下相关评论(感谢Jon Clements):您可以在此处阅读有关深层副本与浅层副本的更多信息

Extra to take into account the relevant comment below (thanks Jon Clements): you can read more about deep copies vs shallow copies here Understanding dict.copy() - shallow or deep?

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

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