簡體   English   中英

列表元素按照Python中的和排序,如何得到理論序號?

[英]How to get the theoretic serial number of list elements if they were sorted by the sum in Python?

我有一個充滿 numpy arrays 的列表,例如:

lst = [np.array([1, 2, 3, 4, 5]),
       np.array([16, 17, 18, 19, 20]),
       np.array([6, 7, 8, 9, 10]),
       np.array([11, 12, 13, 14, 15])]

我已經嘗試過 sort 和 sorted 函數,但我沒有找到合適的鍵來監視序列號。

如果我根據它們的總和對它們進行排序,我想知道列表的元素(numpy 數組)會放在哪個位置。

考慮到這個例子,我預期的 output 將是:

output = [0, 3, 1, 2]

非常感謝你提前。

更新:為了提高效率,您可能只想調用np.argsort一次。 然后使用結果作為最終 output 的索引。

ind = np.argsort(np.sum(lst, 1))
output = ind[ind]

對元素的總和使用np.argsort兩次:

import numpy as np

lst = [np.array([1, 2, 3, 4, 5]),
       np.array([16, 17, 18, 19, 20]),
       np.array([6, 7, 8, 9, 10]),
       np.array([11, 12, 13, 14, 15])]

print(np.argsort(np.argsort(np.sum(lst, 1))))

Output:

[0 3 1 2]

您可以使用scipy.stats.rankdata

import numpy as np

lst = [np.array([1, 2, 3, 4, 5]),
       np.array([16, 17, 18, 19, 20]),
       np.array([6, 7, 8, 9, 10]),
       np.array([11, 12, 13, 14, 15])]

from scipy.stats import rankdata
out = (rankdata(np.sum(lst, 1))-1).astype(int)

# array([0, 3, 1, 2])

我認為預期的 output 應該是[0,2,3,1]

您可以使用排序

import numpy as np
list_ = [np.array([1, 2, 3, 4, 5]), np.array([16, 17, 18, 19, 20]), np.array([6, 7, 8, 9, 10]), np.array([11, 12, 13, 14, 15])]
print([i for i, _ in sorted(zip(range(len(list_)), list_), key=lambda x: sum(x[1]))])

暫無
暫無

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

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