考慮numpy來解決這個問題:import numpy as np
y = [
[1, 2, 3],
[1, 2, 3],
[3, 4, 5],
[6, 5, 4],
[4, 2, 5],
[4, 2, 5],
[1, 2, 8],
[1, 2, 3]
]
# Returns unique values of array, indices of that
# array, and the indices that would rebuild the original array
unique, indices, inverse = np.unique(y, axis=0, return_index=True, return_inverse=True)
下面是每個變數的列印輸出:unique = [
[1 2 3]
[1 2 8]
[3 4 5]
[4 2 5]
[6 5 4]]
indices = [0 6 2 4 3]
inverse = [0 0 2 4 3 3 1 0]
如果我們看看逆變數,可以看到我們確實得到了[0.1.7]作為第一個唯一元素[1 ,2 ,3]的索引位置,我們現在需要做的就是對它們進行適當的分組。new_list = []
for i in np.argsort(indices):
new_list.append(np.where(inverse == i)[0].tolist())
輸出:new_list = [[0, 1, 7], [2], [3], [4, 5], [6]]