在python中使用numpy创建动态数组 [英] Creating a dynamic array using numpy in python

查看:126
本文介绍了在python中使用numpy创建动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个没有大小规格的动态数组.在该数组中,我需要在需要的任何位置插入元素.它们中的其余值可以为null或未定义,直到获得分配给它的值为止.

I want to create a dynamic array without size specification. In that array, I need to insert elements at any point I require. The remaining values in them can be either null or undefined till it gets a value assigned to it.

例如:

a = np.array([])

np.insert(a, any index value, value)

因此,如果我使用 np.insert(a,5,1),我应该得到的结果为:

So, if I use np.insert(a, 5, 1) I should get the result as:

array([null, null, null, null, null, 1])

推荐答案

在MATLAB/Octave中,您可以使用索引创建和扩展矩阵:

In MATLAB/Octave you can create and extend a matrix with indexing:

>> a = []
a = [](0x0)
>> a(5) = 1
a =
   0   0   0   0   1

也就是说,如果您在当前端以外的位置索引一个插槽,它将扩展矩阵,并用0填充它.

That is if you index a slot beyond the current end, it expands the matrix, and fills it with 0s.

JavaScript(在Nodejs会话中)执行类似的操作

Javascript (in a Nodejs session) does something similar

> var a = [1,2];
undefined
> a
[ 1, 2 ]
> a[6] = 1
1
> a
[ 1, 2, , , , , 1 ]
> a[3]
undefined

未定义中间插槽.

Python字典可以通过索引简单地增长

A Python dictionary can grow simply by indexing

In [113]: a = {0:1, 1:2}
In [114]: a[5]=1
In [115]: a
Out[115]: {0: 1, 1: 2, 5: 1}
In [116]: a[3]
...
KeyError: 3
In [117]: a.get(3,None)

字典还实现了 setdefault defaultdict .

Python 列表通过 append extend

A Python list grows by append and extend

In [120]: a = [1,2]
In [121]: a.append(3)
In [122]: a
Out[122]: [1, 2, 3]
In [123]: a.extend([0,0,0,1])
In [124]: a
Out[124]: [1, 2, 3, 0, 0, 0, 1]

列表也会使用 del 和切片分配来更改大小,例如 a [1:2] = [0,0,0,2] .

Lists also change size with del and sliced assignment, e.g. a[1:2] = [0,0,0,2].

一个numpy数组的大小是固定的.要增加一个数组,您必须通过串联创建一个新数组

A numpy array is fixed in size. To grow one, you have to make a new array by concatenation

In [125]: a = np.arange(3)
In [126]: a
Out[126]: array([0, 1, 2])
In [127]: a = np.concatenate((a, [0,0,1]))
In [128]: a
Out[128]: array([0, 1, 2, 0, 0, 1])

数组函数(如 append stack delete insert )使用某种形式的 concatenate 或分配n-fill.

Array functions like append, stack, delete and insert use some form of concatenate or allocate-n-fill.

在有限的情况下,可以调整数组的大小(但是这种方法很少使用):

In restricted cases an array can be resized (but this method is not used very often):

In [161]: a.resize(10)
In [162]: a[-1]=10
In [163]: a
Out[163]: array([ 0,  1,  2,  0,  0,  1,  0,  0,  0, 10])

这篇关于在python中使用numpy创建动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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