You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python/Numpy中为数组元素分配字符串、排序并对应显示?

Solution: Preserve Value-String Mapping with Sort Indices

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:

  1. 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→str3
    
  2. Get the indices that sort P in descending order:

    sorted_indices = np.argsort(-P)  # Returns [1, 0, 2] (positions of largest to smallest values in P)
    
  3. 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"]
    
  4. (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 23:31:05