是否有一个 numpy 函数可以让您指定开始、步骤和编号? [英] Is there a numpy function that allows you to specify start, step, and number?
问题描述
我们都熟悉 np.linspace
,它创建一个给定 start
、stop
和 num<的数组/code> 元素:
We're all familiar with np.linspace
, which creates an array given a start
, stop
, and num
of elements:
In [1]: import numpy as np
In [2]: np.linspace(0, 10, 9)
Out[2]: array([ 0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75, 10. ])
同样,谁会忘记 np.arange
,它会创建一个给定 start
、stop
和 step<的数组/代码>:
Likewise, who could ever forget np.arange
, which creates an array given a start
, stop
, and step
:
In [4]: np.arange(0, 10, 1.25)
Out[4]: array([ 0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75])
但是是否有一个函数可以让您指定 start
、step
和 num
个元素,同时省略 停止
?应该有.
But is there a function that allows you to specify a start
, step
, and num
of elements, while omitting the stop
? There should be.
推荐答案
一个被删除的回答指出 linspace
需要一个 endpoint
参数.
A deleted answer pointed out that linspace
takes an endpoint
parameter.
有了这个,其他答案中给出的两个例子可以写成:
With that, 2 examples given in other answers can be written as:
In [955]: np.linspace(0, 0+(0.1*3),3,endpoint=False)
Out[955]: array([ 0. , 0.1, 0.2])
In [956]: np.linspace(0, 0+(5*3),3,endpoint=False)
Out[956]: array([ 0., 5., 10.])
In [957]: np.linspace(0, 0+(1.25*9),9,endpoint=False)
Out[957]: array([ 0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75, 10. ])
查看numpy.lib.index_tricks
中定义的函数,了解有关如何生成范围和/或网格的其他想法.例如,np.ogrid[0:10:9j]
的行为类似于 linspace
.
Look at the functions defined in numpy.lib.index_tricks
for other ideas on how to generate ranges and/or grids. For example, np.ogrid[0:10:9j]
behaves like linspace
.
def altspace(start, step, count, endpoint=False, **kwargs):
stop = start+(step*count)
return np.linspace(start, stop, count, endpoint=endpoint, **kwargs)
这篇关于是否有一个 numpy 函数可以让您指定开始、步骤和编号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!