看來你是一個接一個地從六個輸入中插入個元素,但是從最後一個元素開始直到每個輸入的第一個元素。基本上這是一個連接過程,零點定期附加(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