如何使从子数组组成的大型数组高效且易读的函数?

时间:2019-06-13 11:44:32

标签: python numpy

我有一个函数,该函数本质上会生成几个较小的numpy数组,并将它们连接在一起成为一个大数组。大致如下:

def make_big_array(second, third):
   big_array = make_first()
   if second:
      big_array +=  make_second()
   if third:
      big_array += make_third()
   return big_array

基本上,我有一个协调器函数,该函数检查big array是否应包括一些子数组,进行创建,然后将它们添加到要返回的big_array中。但是,我认为首先创建每个数组然后将其连接到big_array的末尾是无效的。

我想一种替代方法可能是使用secondthird来锻炼big_array最终将持续多长时间,然后通过make_second()make_third() { {1}}以及从哪里开始填充的索引,但这似乎不太可读。任何人都对如何使其快速且易读有任何建议?

2 个答案:

答案 0 :(得分:1)

您可以分别创建所有数组,然后一次将它们连接起来:

def make_big_array(second, third):
    arrays = [make_first()]
    if second:
        arrays.append(make_second())
    if third:
        arrays.append(make_third())
    return np.concatenate(arrays)

答案 1 :(得分:1)

如本article中所述,建议您预先分配一个数组并将值存储在其中。使用此方法,程序不需要在每次将数组附加到原始数组后都更改数组的大小。您可以针对自己的情况这样做:

.env

但是,只要将两个数组串联起来,通过这种方式获得的效率就可以忽略不计。