如何按照指定字符串的顺序对Numpy数组进行排序?
按自定义字符顺序排序Numpy数组
我有一个Numpy数组:
import numpy as np phrase = np.array(list("eholl")) a = 'hello'
想要按照变量a里的字母顺序(h在前,e次之……)对phrase数组排序,最终得到hello。
我尝试了以下代码:
z = np.sort(phrase, order=a) print(z)
结果触发了错误:
ValueError Traceback (most recent call last) <ipython-input-10-64807c091753> in <module> 2 phrase = np.array(list("eholl")) 3 a = 'hello' ----> 4 z = np.sort(phrase, order=a) 5 6 print(z) <__array_function__ internals> in sort(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in sort(a, axis, kind, order) 996 else: 997 a = asanyarray(a).copy(order="K") ---> 998 a.sort(axis=axis, kind=kind, order=order) 999 return a 1000 ValueError: Cannot specify order when the array has no fields.
问题原因
np.sort的order参数是给带字段的结构化数组用的,你的数组是普通字符数组,没有字段结构,所以用这个参数会报错。
正确实现方式
要按自定义顺序排序,得先给每个字符分配对应优先级(基于a里的位置),再按优先级排序:
import numpy as np phrase = np.array(list("eholl")) a = 'hello' # 建立字符到优先级的映射 char_priority = {char: idx for idx, char in enumerate(a)} # 生成每个字符对应的优先级数组 priorities = np.array([char_priority[c] for c in phrase]) # 用argsort得到排序后的索引,再提取原数组元素 sorted_arr = phrase[np.argsort(priorities)] # 拼接成字符串输出 print(''.join(sorted_arr))
运行后输出:
hello
也可以写成更简洁的版本:
import numpy as np phrase = np.array(list("eholl")) a = 'hello' sorted_arr = phrase[np.argsort(np.array([a.index(c) for c in phrase]))] print(''.join(sorted_arr))
⚠️ 注意:如果phrase里包含a中没有的字符,a.index(c)会抛出异常,需要根据实际需求添加默认处理(比如把这类字符的优先级设为最大值,放到排序结果的最后)。
内容的提问来源于stack exchange,提问作者guerni
相关产品推荐
相关产品推荐

