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

查看:36
本文介绍了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 -> 原始=1,多=2;等等...

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

但是,根据这个问题 此处,Python 的 append() 附加一个指向对象的指针,而不是实际值.所以我将原始代码上的 append(original) 更改为 append(copy):

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天全站免登陆