python - 合并从循环返回的 numpy 数组

标签 python arrays numpy

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

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

返回的数组总是一维的。我想将所有数组组合成一个数组(也是一维的。

我尝试了以下方法,但失败了

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

错误是 ValueError: operands could not be broadcast together with shapes (0) (9095)。我怎样才能让它发挥作用?

例如这两个数组:

[ 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 回答)是使用 list comprehension ,

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

关于python - 合并从循环返回的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22662996/

相关文章:

python - 通过对像素求和来重新调整矩阵

python - 有没有办法在不启动服务器(可能作为库)的情况下使用 postgresql?

Javascript 乘法数组输入

python - 如何使用递归将两个列表添加在一起?

javascript - 将多维数组转换为 HTML 表

c# - 在控制台打印数组

python - 错误名称 'dtype' 未定义

python - 如何使用 PyPlot 绘制带有 2 个 slider 的 4D 数组?

python - 默认的内容类型/字符集是什么?

python - 重置滚动总和