Python如何在for循环中填充数组arr [i,j],该循环计算将放入i和j的值

时间:2016-06-16 17:18:08

标签: python arrays

这是一个必须计算达到一定密度曲线所需的盐水流量的程序。我需要存储的重要变量是Q和t,因为它们将用于告诉我的泵实时运行的速度。

import numpy as np

for z in np.arange(0, 0.5, 0.01):

    Q = a + z    # where a is a predefined number
    t = b + z    # where b is a predefined number

    # here I would like to store Q and t in an array

    for something in arr[i, j]:
        i = t
        j = Q

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题,这应该可以解决问题。

arr = []
for z in np.arange(0, 0.5, 0.01):

    Q = a + z
    t = b + z

    # here I would like to store Q and t in an array
    arr.append([t,Q])

for item in arr:
    i = item[0]
    j = item[1]

它创建一个名为arr的列表,用于存储[Q,t]值的列表。

答案 1 :(得分:0)

多维数组只是数组的数组。

如果将arr定义为看起来像的二维数组:

[ [1, 2],
  [3, 4],
  [5, 6] ]

arr[0]会返回[1,2]

如果你有一个空数组,就像在arr = []中一样,并且你想为它添加一行,你可以添加一个新数组。例如,要生成上面的2D数组,您可以使用代码:

arr = []
arr.append([1,2])
arr.append([3,4])
arr.append([5,6])

在您的问题的上下文中,如果您只需要向数组添加行以保存两个计算值Qt,请使用:

import numpy as np

arr = []

for z in np.arange(0, 0.5, 0.01):

    Q = a + z # where a is a predefined number
    t = b + z # where b is a predefined number

    # here I would like to store Q and t in a 2D array
    arr.append([Q,t])

print arr

但是,如果您可以在循环内完成计算,则根本不需要实例化任何数组。

import numpy as np

for z in np.arange(0, 0.5, 0.01):

    Q = a + z # where a is a predefined number
    t = b + z # where b is a predefined number

    # Do your calculations with Q ant t
    print Q + t # replace with your actual calculations

效率更高,代码更少,设计更容易。

我希望有所帮助。

答案 2 :(得分:0)

您可以使用broadcasting创建一个没有Python循环的二维数组:

#Constants
a = 3
b = 2

使z为二维数组

z = np.array((np.arange(0, 0.1, 0.01),np.arange(0, 0.1, 0.01)))

>>> print(z)
[[ 0.    0.01  0.02  0.03  0.04  0.05  0.06  0.07  0.08  0.09]
 [ 0.    0.01  0.02  0.03  0.04  0.05  0.06  0.07  0.08  0.09]]
>>> 

将常数放在一维数组中

c = np.array((a,b))

>>> print(c)
[3 2]
>>> print(z.shape, z.T.shape, c.shape)
((2, 10), (10, 2), (2,))
>>>

将常量添加到z

qt = z.T + c

>>> print(qt)
[[ 3.    2.  ]
 [ 3.01  2.01]
 [ 3.02  2.02]
 [ 3.03  2.03]
 [ 3.04  2.04]
 [ 3.05  2.05]
 [ 3.06  2.06]
 [ 3.07  2.07]
 [ 3.08  2.08]
 [ 3.09  2.09]]
>>>

for thing in qt:
    print(thing)

>>> 
[ 3.  2.]
[ 3.01  2.01]
[ 3.02  2.02]
[ 3.03  2.03]
[ 3.04  2.04]
[ 3.05  2.05]
[ 3.06  2.06]
[ 3.07  2.07]
[ 3.08  2.08]
[ 3.09  2.09]
>>> 

另一个numpy broadcasting链接。还有许多其他很好的解释那里