Python:附加原始对象与附加对象副本 [英] Python: append an original object vs append a copy of object

查看:64
本文介绍了Python:附加原始对象与附加对象副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,很抱歉,如果这个问题是非常基本的,我只是从Python开始.

First of all, sorry if this questions is extremely basic, I'm just starting with Python.

我在理解Python 3.6如何创建对象并将对象附加到列表上时遇到了问题.请参见以下代码:

I'm having problems understanding how Python 3.6 creates and appends objects to lists. See the following code:

a_dict=dict()
a_list=list()

for i in range(100):
  a_dict['original'] = i
  a_dict['multi'] = i*2
  a_list.append(a_dict)

列表的打印方式类似

print(a_list)
>>[{'original': 99, 'multi': 198}{'original': 99, 'multi': 198}...{'original': 99, 'multi': 198}]

根据我的原始想法,i = 0-> original = 0,multi = 0;i = 1-> original = 1,multi = 2;等等...

According to my original thoughts, i=0 -> original=0, multi=0; i=1 -> original=1, multi=2; etc...

但是,根据此问题

But, according to this question here, Python's append() appends a pointer to the object not the actual value. So I change the append(original) on my original code to append(copy):

a_dict=dict()
a_list=list()

for i in range(100):
  a_dict['original'] = i
  a_dict['multi'] = i*2
  a_list.append(a_dict.copy()) ##change here

现在,我得到了预期的结果:

Now, I get the desired result:

print(a_list)
[{'original': 0, 'multi': 0}, {'original': 1, 'multi': 2}, {'original': 2, 'multi': 4},...]    

现在,这是我的问题:

append()如何真正起作用?列表是否总是包含指向其原始对象的类似指针的对象?其他类型呢?如果我的意图不是直接与原始值或我正在使用的列表/容器混淆,是否应该始终使用copy()?

How append() really works? Do always lists contain pointers-like objects to their originals? How about other types? Should I always use copy() if my intentions are not to directly mess with the original values or the list/container I'm using?

希望我对自己的解释足够好.再次抱歉,这是一个基本问题.谢谢.

Hope I'm explaining myself good enough. And again sorry if it's a basic question. Thanks.

推荐答案

这与您添加的对象的可变性有关.如果对象是可变的,则可以对其进行更新,并且实际上您可以使用 .append()函数添加对列表的引用.因此,在这种情况下,您需要一份副本.

This has to do with mutability of the objects you append. If the objects are mutable, they can be updated, and you essentially add a reference to your list with the .append() function. Thus in these situations you need a copy.

A pretty good list of which types are mutable and not is found on this site. However, generally, container types tend to be mutable whereas simple values typically are immutable.

这篇关于Python:附加原始对象与附加对象副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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