一个可能的且只有内存不是时间密集型的解决方案是使用np.repeat
和np.resize
来重复数组a和b,并将其重新调整为最终形状的大小,然后简单地添加这两个数组。
代码:
import numpy as np
a = np.array([0, 10, 20])
b = np.array([20, 30, 40, 50])
def extend_and_add(a, b):
return np.repeat(a, len(b)) + np.resize(b, len(a)*len(b))
所以extend_and_add(a, b)
回报:
extend_and_add(a, b)
> array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])
说明:
基本上np.repeat(a, len(b))
重复:
a
> array([ 0, 10, 20])
到
np.repeat(a, len(b))
> array([ 0, 0, 0, 0, 10, 10, 10, 10, 20, 20, 20, 20])
在此之后,你需要np.resize
调整第二阵列:
b
> array([20, 30, 40, 50])
调整为:
np.resize(b, len(a)*len(b))
> array([20, 30, 40, 50, 20, 30, 40, 50, 20, 30, 40, 50])
现在,我们可以简单地添加数组:
个
array([ 0, 0, 0, 0, 10, 10, 10, 10, 20, 20, 20, 20])
+
array([20, 30, 40, 50, 20, 30, 40, 50, 20, 30, 40, 50])
回报:
array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])
这有什么错'for'循环? – TigerhawkT3
你的数组是什么? numpy,array.array? –
在列表解析中做'for'计数? ;) – Pynchia