有什么方法可以使用Numpy数组制作软引用或类似Pointer的对象吗? [英] Is there any way to make a soft reference or Pointer-like objects using Numpy arrays?

查看:99
本文介绍了有什么方法可以使用Numpy数组制作软引用或类似Pointer的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以将许多不同数组中的数据引用到一个数组中,但又不会复制它.

I was wondering whether there is a way to refer data from many different arrays to one array, but without copying it.

示例:

import numpy as np
a = np.array([2,3,4,5,6])
b = np.array([5,6,7,8])

c = np.ndarray([len(a)+len(b)])

offset = 0
c[offset:offset+len(a)] = a
offset += len(a)
c[offset:offset+len(b)] = b

但是,在上面的示例中,c是一个新数组,因此,如果您修改ab的某些元素,则根本不会在c中对其进行修改.

However, in the example above, c is a new array, so that if you modify some element of a or b, it is not modified in c at all.

我希望c的每个索引(即c[0]c[1]等)都引用ab的每个元素,但就像一个指针一样,而不必创建数据.

I would like that each index of c (i.e. c[0], c[1], etc.) refer to each element of both a and b, but like a pointer, without making a deepcopy of the data.

推荐答案

正如@Jaime所说,您无法生成一个新数组,其内容指向多个现有数组中的元素,但是您可以执行相反的操作:

As @Jaime says, you can't generate a new array whose contents point to elements in multiple existing arrays, but you can do the opposite:

import numpy as np

c = np.arange(2, 9)
a = c[:5]
b = c[3:]
print(a, b, c)
# (array([2, 3, 4, 5, 6]), array([5, 6, 7, 8]), array([2, 3, 4, 5, 6, 7, 8]))

b[0] = -1

print(c,)
# (array([ 2,  3,  4, -1,  6,  7,  8]),)


我认为您要求的基本问题是numpy数组必须由连续的内存块(可以是


I think the fundamental problem with what you're asking for is that numpy arrays must be backed by a continuous block of memory that can be regularly strided in order to map memory addresses to the individual array elements.

在您的示例中,ab将被分配在不相邻的内存块中,因此将无法使用一组大步来解决它们的元素.

In your example, a and b will be allocated within non-adjacent blocks of memory, so there will be no way to address their elements using a single set of strides.

这篇关于有什么方法可以使用Numpy数组制作软引用或类似Pointer的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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