簡體   English   中英

如何將字符串分配給數組中的不同元素,對數組進行排序,然后根據 Python/Numpy 中的排序顯示字符串?

[英]How can I assign strings to different elements in an array, sort the array, then display the strings based on the sort in Python/Numpy?

我有一個數組P = np.array([2,3,1])並且我想分別為每個元素分配三個字符串。 所以,:

"str1", "str2", "str3" = P

對數組排序后:

In[]: P = -np.sort(-P)
Out[]: [3,2,1]

然后我希望能夠顯示基於這種排序的字符串,如:

Out[]: "str2","str1","str3",

嘗試為元素分配變量名稱,但它不會按預期顯示在 output 上。 嘗試用字符串作為元素定義對象數組,但無法將它們分配給 P 的數值。

您可以使用numpy.argsort

import numpy as np
P = np.array([2,3,1])
S = np.array(["str1", "str2", "str3"])

sort_idx = np.argsort(-P)
print(S[sort_idx])
# ['str2' 'str1' 'str3']

暫無
暫無

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

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