簡體   English   中英

從二維數組創建元組列表

[英]Create list of tuples from 2d array

我正在尋找從2xn數組創建元組的列表,其中第一行是ID,第二行是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)]

有人有創意,快速的方法嗎?

謝謝!

標准的(很抱歉,不是創造性的,但相當快)但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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM