2016-02-15 115 views
2

我有一個巨大的數組,但爲了說明,我使用了一個大小爲14的數組。我有另一個包含2,3,3,6的列表。我如何高效地無需創建列表新陣列,使得:Python:創建子陣列列表

import numpy as np 
A = np.array([1,2,4,5,7,1,2,4,5,7,2,8,12,3]) # array with 1 axis 
subArraysizes = np.array(2, 3, 3, 6) #sums to number of elements in A 
B = list() 
B[0] = [1,2] 
B[1] = [4,5,7] 
B[2] = [1,2,4] 
B[3] = [5,7,2,8,12,3] 

中選擇即從它的儲存在B首先2個元件中,選擇一個存儲在它B等中它出現在A的順序的下一個3個元素

回答

3

您可以使用np.split -

B = np.split(A,subArraysizes.cumsum())[:-1] 

樣品運行 -

In [75]: A 
Out[75]: array([ 1, 2, 4, 5, 7, 1, 2, 4, 5, 7, 2, 8, 12, 3]) 

In [76]: subArraysizes 
Out[76]: array([2, 3, 3, 6]) 

In [77]: np.split(A,subArraysizes.cumsum())[:-1] 
Out[77]: 
[array([1, 2]), 
array([4, 5, 7]), 
array([1, 2, 4]), 
array([ 5, 7, 2, 8, 12, 3])]