拉风的咖菲猫
import numpy as npdata = [ ['Australia', 6.0], ['Brazil', 3.0], ['China', 269.0], ['France', 303.0], ['India', 76.0], ['Iran', 14.0], ['Israel', 11.0], ['Japan', 126.0], ['Kazakhstan', 701.0], ['Kenya', 9.0], ['New Zealand', 13.0], ['North Korea', 5.0], ['Pacific Ocean', 36.0], ['Russian Federation', 1398.0], ['South Korea', 3.0], ['USA', 1351.0]]我们可以创建一个结构化数组,然后按键对其进行排序:dtype = [ ('name', '<U18'), ('rockets', float)]data = np.array([tuple(x) for x in data], dtype=dtype) sorted_data = np.sort(data, order=['rockets']) print(sorted_data)
侃侃尔雅
使用 python 列表排序很容易:In [208]: alist = [ ['Australia', 6.0], ...: ['Brazil', 3.0], ...: ['China', 269.0], ...: ['France', 303.0], ...: ['India', 76.0], ...: ['Iran', 14.0], ...: ['Israel', 11.0], ...: ['Japan', 126.0], ...: ['Kazakhstan', 701.0], ...: ['Kenya', 9.0], ...: ['New Zealand', 13.0], ...: ['North Korea', 5.0], ...: ['Pacific Ocean', 36.0], ...: ['Russian Federation', 1398.0], ...: ['South Korea', 3.0], ...: ['USA', 1351.0]]In [209]: newlist = sorted(alist, key=lambda x: x[1])In [210]: newlistOut[210]: [['Brazil', 3.0], ['South Korea', 3.0], ['North Korea', 5.0], ['Australia', 6.0], ['Kenya', 9.0], ['Israel', 11.0], ['New Zealand', 13.0], ['Iran', 14.0], ['Pacific Ocean', 36.0], ['India', 76.0], ['Japan', 126.0], ['China', 269.0], ['France', 303.0], ['Kazakhstan', 701.0], ['USA', 1351.0], ['Russian Federation', 1398.0]]使用对象 dtype 数组(保留字符串和浮点列):In [211]: arr = np.array(alist, object)In [212]: arrOut[212]: array([['Australia', 6.0], ['Brazil', 3.0], ['China', 269.0], ['France', 303.0], ... ['USA', 1351.0]], dtype=object)只需查看第二列即可获取排序索引:In [213]: idx = np.argsort(arr[:,1])In [214]: idxOut[214]: array([ 1, 14, 11, 0, 9, 6, 10, 5, 12, 4, 7, 2, 3, 8, 15, 13])In [215]: arr[idx]Out[215]: array([['Brazil', 3.0], ['South Korea', 3.0], ['North Korea', 5.0], ['Australia', 6.0], ['Kenya', 9.0], ... ['Russian Federation', 1398.0]], dtype=object)其他答案中的结构化数组方法也很好。