Numpy vs内置副本列表 [英] Numpy vs built-in copy list

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

问题描述

以下代码有什么区别

内置列表代码

built-in list code

>>> a = [1,2,3,4]
>>> b = a[1:3] 
>>> b[1] = 0
>>> a
[1, 2, 3, 4]
>>> b
[2, 0]

numpy数组

numpy array

>>> c = numpy.array([1,2,3,4])
>>> d = c[1:3]
>>> d[1] = 0
>>> c
array([1, 2, 0, 4])
>>> d
array([2, 0])

正如在numpy数组c中看到的那样,

是直接实现的.我认为在内置列表中,为变量b分配了新的内存.可能是在numpy中,对c [1:3]的引用分配了d,对此我不清楚. 它如何用于numpy和内置?

as it is seen in numpy array c is effected directly. I think in built-in lists, new memory is allocated for the variable b. Probably in numpy the reference of c[1:3] is assigned d, I am not clear about these. How this works for numpy and built-in?

推荐答案

要理解的关键点是,Python中的每个分配都将名称与内存中的对象相关联. Python永远不会在分配时进行复制.现在,了解何时创建新对象及其行为方式变得很重要.

The key point to understand is that every assignment in Python associates a name with an object in memory. Python never copies on assignment. It now becomes important to understand when new objects are created and how they behave.

在您的第一个示例中,列表中的切片将创建一个新的列表对象.在这种情况下,两个列表都引用某些相同的对象(int 2和int 3).复制这些引用的事实就是所谓的浅"副本.换句话说,引用被复制,但是引用的对象仍然相同.请记住,不管列表中存储的是什么类型,这都是正确的.

In your first example, the slicing in the list creates a new list object. In this case, both of the lists reference some of the same objects (the int 2 and the int 3). The fact that these references are copied is what is called a "shallow" copy. In other words, the references are copied, but the objects they refer to are still the same. Keep in mind that this will be true regardless of the type of thing that is stored in the list.

现在,我们创建一个新对象(int 0)并分配b[1] = 0.由于ab是单独的列表,因此它们现在显示不同的元素也就不足为奇了.

Now, we create a new object (the int 0) and assign b[1] = 0. Because a and b are separate lists, it should not surprise us that they now show different elements.

我喜欢在数组的情况下,通过基本切片生成的所有数组都是始终查看原始数组的视图." .

此新对象与原始对象共享数据,并且对索引分配的处理方式是对视图的任何更新都会更新共享的数据.

This new object shares data with the original, and indexed assignment is handled in such a way that any updates to the view will update the shared data.

这篇关于Numpy vs内置副本列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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