合并从循环返回的Numpy数组

问题描述:

我有一个生成numpy数组的循环:

I have a loop that generates numpy arrays:

for x in range(0, 1000):
   myArray = myFunction(x)

返回的数组始终是一维的.我想将所有数组组合成一个数组(也是一维的.)

The returned array is always one dimensional. I want to combine all the arrays into one array (also one dimensional.

我尝试了以下操作,但失败了

I tried the following, but it failed

allArrays = []
for x in range(0, 1000):
   myArray = myFunction(x)
   allArrays += myArray

错误为ValueError: operands could not be broadcast together with shapes (0) (9095).我怎样才能使它正常工作?

The error is ValueError: operands could not be broadcast together with shapes (0) (9095). How can I get that to work?

例如,这两个数组:

[ 234 342 234 5454 34 6]
[ 23 2 1 4 55 34]

应合并到此数组中:

[ 234 342 234 5454 34 6 23 2 1 4 55 34 ]

您可能是说

allArrays = np.array([])
for x in range(0, 1000):
    myArray = myFunction(x)
    allArrays = np.concatenate([allArrays, myArray])

一种更简洁的方法(请参见wims答案)是使用列表理解力

A more concise approach (see wims answer) is to use a list comprehension,

allArrays = np.concatenate([myFunction(x) for x in range])