如何在Python/Numpy中为数组元素分配字符串、排序并对应显示?
Instead of assigning variables directly to array elements (which breaks the link when sorted), use indices to keep track of which string corresponds to which value. Here's a straightforward approach:
Define your original array and matching string list (order must align with the array elements):
import numpy as np P = np.array([2, 3, 1]) strings = ["str1", "str2", "str3"] # 2→str1, 3→str2, 1→str3Get the indices that sort
Pin descending order:sorted_indices = np.argsort(-P) # Returns [1, 0, 2] (positions of largest to smallest values in P)Apply these indices to sort both the array and the string list:
sorted_P = P[sorted_indices] # Result: [3, 2, 1] sorted_strings = [strings[i] for i in sorted_indices] # Result: ["str2", "str1", "str3"](Optional) Print the paired results:
for val, s in zip(sorted_P, sorted_strings): print(f"{val} → {s}")
This method works because np.argsort(-P) gives you the original positions of elements in the sorted order. By reusing these indices for both the array and strings, you maintain the correct value-string mapping.
内容的提问来源于stack exchange,提问作者Dordini Balbozhia

