栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

何时使用copy.copy

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

何时使用copy.copy

基本上,

b = a
指向的
b
是任何
a
指向的地方,没有别的。

您要问的是可变类型。数字,字符串,元组,frozensets,布尔值

None
,是不可变的。列表,字典,集合,字节数组是可变的。

如果我将类型设为可变,例如

list

>>> a = [1, 2]  # create an object in memory that points to 1 and 2, and point a at it>>> b = a       # point b to wherever a points>>> a[0] = 2    # change the object that a points to by pointing its first item at 2>>> a[2, 2]>>> b[2, 2]

他们都将仍然指向同一项目。

我也会评论您的原始代码:

>>>a=5     # '5' is interned, so it already exists, point a at it in memory>>>b=a     # point b to wherever a points>>>a=6     # '6' already exists in memory, point a at it>>>print b # b still points at 5 because you never moved it5

通过执行操作,您始终可以看到内存中指向的位置

id(something)

>>> id(5)77519368>>> a = 5>>> id(a)77519368     # the same as what id(5) showed us, 5 is interned>>> b = a>>> id(b)77519368     # same again>>> id(6)77519356>>> a = 6>>> id(a)77519356     # same as what id(6) showed us, 6 is interned>>> id(b)77519368     # still pointing at 5.    >>> b5

您可以使用

copy
,当你想要做一个结构的副本。但是,它
仍然不会复制被 拘禁 的东西
。这包括整数小于
256
True
False
None
,短字符串喜欢
a
。基本上,除非您确定不会被实习生搞砸 否则几乎
应该 使用它

再看一个示例,该示例即使使用可变类型也可以显示,将一个变量指向新变量仍然不会更改旧变量:

>>> a = [1, 2]>>> b = a>>> a = a[:1]    # copy the list a points to, starting with item 2, and point a at it>>> b # b still points to the original list[1, 2]>>> a[1]>>> id(b)79367984>>> id(a)80533904

切片列表(无论何时使用

:
)都会复制一份。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/455870.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号