先使用zip函数将列表索引和元素聚合在一起,然后转换回列表类型,tmp=[(索引, 元素),…]然后利用sorted函数按照tmp列表中的每个元素的第二位进行排序。
test = [41,65,2,8,12,1,534,76,89,4,2] # 先将索引和列表元素对应起来 tmp = list(map(list,zip(range(len(test)), test))) # 从大到小排序 large = sorted(tmp,key=lambda x:x[1],reverse=True) print(large5) # 从小到大排序 small = sorted(tmp,key=lambda x:x[1],reverse=False) print(small5)
结果:
[[6, 534], [8, 89], [7, 76], [1, 65], [0, 41], [4, 12], [3, 8], [9, 4], [2, 2], [10, 2], [5, 1]] [[5, 1], [2, 2], [10, 2], [9, 4], [3, 8], [4, 12], [0, 41], [1, 65], [7, 76], [8, 89], [6, 534]]方法二:heapq库
先使用zip函数将列表索引和元素聚合在一起,然后转换回列表类型,tmp=[(索引, 元素),…]调用heapq库的堆排序,按照tmp列表中的每个元素的第二位进行排序。
import heapq # 最大5个 test = [41,65,2,8,12,1,534,76,89,4,2] tmp = zip(range(len(test)), test) large5 = heapq.nlargest(5, tmp, key=lambda x:x[1]) print(large5) # 最小5个 test = [41,65,2,8,12,1,534,76,89,4,2] tmp = zip(range(len(test)), test) small5 = heapq.nsmallest(5, tmp, key=lambda x:x[1]) print(small5) # P.S. 调用一次heapq.nlargest或heapq.nsmallest之后tmp将被清空。
结果:
[(6, 534), (8, 89), (7, 76), (1, 65), (0, 41)] [(5, 1), (2, 2), (10, 2), (9, 4), (3, 8)]



