2017-04-16 78 views
0

我正在创建一个2xn数组的元组列表,其中第一行是一个ID,第二行是这个ID组的分配。我想创建一个组织分配给他们小组的ID的列表。从二维数组创建元组列表

例如:

array([[ 0., 1., 2., 3., 4., 5., 6.], 
     [ 1., 2., 1., 2., 2., 1., 1.]) 

在上述示例中,ID 0分配给组1,ID 1至组2,依此类推。输出列表看起来像:

a=[(0,2,5,6),(1,3,4)] 

没有人有任何创造性的,快速的方法来做到这一点?

谢谢!

回答

1

标准(对不起,没有创意 - 但相当快)numpy的方式将是一个间接的排序:

import numpy as np 

data = np.array([[ 0., 1., 2., 3., 4., 5., 6.], 
       [ 1., 2., 1., 2., 2., 1., 1.]]) 

index = np.argsort(data[1], kind='mergesort') # mergesort is a bit 
               # slower than the default 
               # algorithm but is stable, 
               # i.e. if there's a tie 
               # it will preserve order 
# use the index to sort both parts of data 
sorted = data[:, index] 
# the group labels are now in blocks, we can detect the boundaries by 
# shifting by one and looking for mismatch 
split_points = np.where(sorted[1, 1:] != sorted[1, :-1])[0] + 1 

# could convert to int dtype here if desired 
result = map(tuple, np.split(sorted[0], split_points)) 
# That's Python 2. In Python 3 you'd have to explicitly convert to list: 
# result = list(result) 
print(result) 

打印:

[(0.0, 2.0, 5.0, 6.0), (1.0, 3.0, 4.0)]