看来你是一个接一个地从六个输入中插入个元素,但是从最后一个元素开始直到每个输入的第一个元素。基本上这是一个连接过程,零点定期附加(2+6
)。
一种方法能够有效地做到这一点,而不是循环,将与np.concatenate
-
size = len(b0) # Must be 4096
# Initialize output as a 2D array with zeros that would also hold all elements
# from the six inputs
out = np.zeros((size,8),dtype=b0.dtype)
# Leave first two elements in each row and
# put inputs-concatenated and flipped version into the output array
out[:,2:] = np.concatenate((b0,b1,r0,g0,r1,g1)).reshape(-1,size)[:,::-1].T
# Finally convert to list if needed
data_bin_out = out.ravel().tolist()
运行测试和验证输出 -
1)设置输入:
In [2]: # Inputs
...: size = 4096
...: b0 = np.random.randint(2,9,(size))
...: b1 = np.random.randint(2,9,(size))
...: r0 = np.random.randint(2,9,(size))
...: g0 = np.random.randint(2,9,(size))
...: r1 = np.random.randint(2,9,(size))
...: g1 = np.random.randint(2,9,(size))
...:
2 )定义方法 -
def concat_app(b0,b1,r0,g0,r1,g1):
out = np.zeros((size,8),dtype=b0.dtype)
out[:,2:] = np.concatenate((b0,b1,r0,g0,r1,g1)).reshape(-1,size)[:,::-1].T
return out.ravel().tolist()
def org_app(b0,b1,r0,g0,r1,g1):
data_bin = []
counter = 0
for x in range(size):
counter += 1
data_bin.insert(0, 0)
data_bin.insert(1, 0)
data_bin.insert(2, b0[x])
data_bin.insert(3, b1[x])
data_bin.insert(4, r0[x])
data_bin.insert(5, g0[x])
data_bin.insert(6, r1[x])
data_bin.insert(7, g1[x])
return data_bin
3)时序和验证:
In [4]: %timeit org_app(b0,b1,r0,g0,r1,g1)
1 loops, best of 3: 556 ms per loop
In [5]: %timeit concat_app(b0,b1,r0,g0,r1,g1)
1000 loops, best of 3: 648 µs per loop
In [6]: concat_app(b0,b1,r0,g0,r1,g1) == org_app(b0,b1,r0,g0,r1,g1)
Out[6]: True
所以,基本上你要'zip'和'chain'阵列?有点像'[x for y in zip([1,3,5],[2,4,6])for x in y]',快一点,用numpy? –
我还不确定你的第一个例子与第二个例子相关。你确定预定的订单是正确的吗? 'r0,r1,g0,g1,b0,b1'与'a'和'b'有什么关系? –
@tobias_k对不起,第一个例子只是它应该做的一个演示,第二个例子来自我的代码,我没有改变什么。所以orde应该像'code [0,0,b0 [x],b1 [x],r0 [x],g0 [x],r1 [x],g1 [x]](前两位是抵消)。然后重复,直到x = 4096 – InvAdErZz