我有一个函数,它返回许多大小不同的输出数组。你知道吗
arr1,arr2,arr3,arr4,arr5, ... = func(data)
我想在数据的时间序列上多次运行这个函数,并将每个输出变量组合成一个覆盖整个时间序列的数组。你知道吗
详细说明:如果在调用函数时,输出arr1有维数(x,y),我想运行函数't'次,最后得到一个有维数(x,y,t)的数组。大小为(x,y)的“t”数组列表也是可以接受的,但不是首选。你知道吗
同样,输出数组并非都具有相同的维数,甚至维数也不相同。Arr2可能有大小(x2,y2),arr3可能只是长度的向量(x3)。我不知道所有这些数组的大小。你知道吗
我目前的解决方案是这样的:
arr1 = []
arr2 = []
arr3 = []
...
for t in range(t_max):
arr1_t, arr2_t, arr3_t, ... = func(data[t])
arr1.append(arr1_t)
arr2.append(arr2_t)
arr3.append(arr3_t)
...
等等。然而,当对每个输出阵列重复27次时,这看起来并不美观。你知道吗
有没有更好的办法?你知道吗
你可以把
arr1
,arr2
等列成一个列表(向量或矩阵或任何东西)。然后使用循环迭代从func
获得的结果,并将它们添加到各个列表中。你知道吗不同子列表中的元素不必具有相同的维度。你知道吗
这个答案给出了一个使用structured arrays的解决方案。它有以下要求:即使一个函数
f
返回N
数组,并且每个返回数组的大小可以不同,那么对于f
的所有结果,len(array_i)
必须始终相同。例如如果上述情况属实,则可以使用结构化数组。结构化数组类似于普通数组,只是具有复杂的数据类型。例如,我可以指定一个数据类型,它由一个shape
5
的int数组和另一个shape(2, 2)
的float数组组成。例如使用
dtype
可以创建一个结构化数组,并一次性设置结构化数组上的所有结果。你知道吗不确定它是否算作“优雅”,但您可以构建结果
tuple
的list
,然后使用zip
按返回位置而不是按调用号将它们分组到tuple
,然后可选地map
将这些tuple
转换为最终的数据类型。例如,对于numpy
array
:如果在给定位置从func返回的元素可能有不一致的维度(例如,一个调用可能返回10x10作为第一个返回,另一个返回5x5),那么您应该避免最后的
map
步骤(因为array
没有一致的维度,只需将第二个到最后一个步骤替换为:使
arr#
成为tuple
的2Darray
,或者如果需要可变:使它们成为2D
array
的list
相关问题 更多 >
编程相关推荐