Python迭代不同大小的数组

时间:2018-03-06 18:31:31

标签: python arrays iteration calculation

我正在尝试执行简单的计算并将输出放入数组中。

我首先设置值和数组,然后迭代数组并执行计算。最后,我尝试将计算出的输出放入一个填充零的数组中。但是,我收到以下错误消息:

"对于范围内的i(b [0]):TypeError:只能将整数标量数组转换为标量索引。"

有人可以帮我理解如何正确迭代数组并执行计算吗?谢谢你的时间。

import numpy as np


S = np.linspace(0,37,100)
T = np.array([5.,25.,30.])


delta = 25. - T
f = 1575e6

tt = T.reshape(3,1)
beta = S*tt
b = np.zeros(np.shape(beta)).reshape(100,3)

#Calculate and put into a 3x100 or 100x3 array
for i in range(b[0]):
      for j in range(T[0]):
            b[i,j]= 1.00 + 2.282e-5*S[i]*[j] - 7.638e-4*S[i] - 7.76e-6*S[i]**2 + 1.105e-8*S[i]**3

1 个答案:

答案 0 :(得分:0)

我有点不清楚你究竟在做什么,但我能够调整你的代码并让它发挥作用。首先,T[0]是一个浮点数(.5),不适用于迭代器。我假设您想循环遍历每个变量的长度以使b 100x3,在这种情况下您应该使用range(len(b[0])),或使用变量来定义b[0]的长度,并且使用该变量来定义迭代器。

此外,在最后一行中,您将j放在括号中,使其成为一个列表,如果您希望将其作为数字相乘,则不需要该列表。您是否希望迭代器(0,1,2)乘以S[i]T中的特定值?我在下面写了前者,但是如果你想让后者改为jT[j]

以下代码运行时没有错误

import numpy as np


S = np.linspace(0,37,100)
T = np.array([5.,25.,30.])


delta = 25. - T
f = 1575e6

tt = T.reshape(3,1)
beta = S*tt
length_of_b_0=100
b = np.zeros(np.shape(beta)).reshape(length_of_b_0,3)

#Calculate and put into a 3x100 or 100x3 array
for i in range(length_of_b_0):
      for j in range(len(T)):
            b[i,j]= 1.00 + 2.282e-5*S[i]*j - 7.638e-4*S[i] - 7.76e-6*S[i]**2 + 1.105e-8*S[i]**3