为linspace和for循环范围问题输入numpy数组



我在尝试使用多个值进行测试时遇到了问题,因为循环中的linspace和range不接受数组作为输入。

下面是我尝试做的一个例子:

gp_input = np.array([31,61])
def var_gp(gp):
for i in gp:
x_l = np.linspace(0,3,gp)
...
for i in range(gp):
...

错误告诉我什么:

Traceback (most recent call last):

文件";变量gp.py";,第306行,invar_gp(gp_input(

File "variable gp.py", line 18, in var_gp
x_l = np.linspace(0,3,gp)
File "<__array_function__ internals>", line 5, in linspace
File "/home/rjomega/anaconda3/lib/python3.8/site-packages/numpy/core/function_base.py", line 120, in linspace
num = operator.index(num)
TypeError: only integer scalar arrays can be converted to a scalar index

如果我只是手动更改gp的值,并希望我能插入尽可能多的值来尝试,感觉这将成为一个坏习惯。非常感谢。

链接到完整的代码

如果我只是手动更改gp的值,而不使用def函数,它会很好

如果你也遇到这种问题,我找到了解决方案:

for i in gp:
gp = i
x_l = np.linspace(0,3,gp)
...
for i in range(gp):
...

添加gp=i似乎绕过了问题

对于作为数组或列表的gp,迭代如下:

In [471]: gp = np.array([3,6])
In [472]: for i in gp:
...:     print(i)
...:     xi = np.linspace(0,3,i)
...:     print(xi)
...: 
3
[0.  1.5 3. ]
6
[0.  0.6 1.2 1.8 2.4 3. ]

请注意,我在调用linspace时使用i,而不是gp

当我们将数组传递给linspace时,我们会得到您的错误:

In [473]: np.linspace(0,3,gp)
Traceback (most recent call last):
File "<ipython-input-473-7032efa38f7c>", line 1, in <module>
np.linspace(0,3,gp)
File "<__array_function__ internals>", line 5, in linspace
File "/usr/local/lib/python3.8/dist-packages/numpy/core/function_base.py", line 120, in linspace
num = operator.index(num)
TypeError: only integer scalar arrays can be converted to a scalar index

通常,在for i in gp:表达式中,不要将gp与正文一起使用。您希望使用i,迭代变量。使用for循环的全部目的是使用gp的元素,而不是整个内容。

我们也不能在range中使用该数组。它必须是数字元素,一次一个:

In [477]: range(gp)
Traceback (most recent call last):
File "<ipython-input-477-4e92b04fe1fc>", line 1, in <module>
range(gp)
TypeError: only integer scalar arrays can be converted to a scalar index
In [478]: for i in gp:
...:     print(list(range(i)))
...: 
[0, 1, 2]
[0, 1, 2, 3, 4, 5]

如果您也遇到这种问题,我找到了解决方案:

for i in gp:
gp = i
x_l = np.linspace(0,3,gp)
...
for i in range(gp):
...

添加gp=i似乎绕过了问题

最新更新