1 # -*- coding: utf-8 -*- 2 import heapq 3 4 nums = [1, 8, 2, 23, 7, -4, 18, 23, 24, 37, 2] 5 6 # 最大的3个数的索引 7 max_num_index_list = map(nums.index, heapq.nlargest(3, nums)) 8 9 # 最小的3个数的索引 10 min_num_index_list = map(nums.index, heapq.nsmallest(3, nums)) 11 12 print(list(max_num_index_list)) 13 print(list(min_num_index_list))
import heapq a=[1,2,3,4,5] re1 = map(a.index, heapq.nlargest(3, a)) #求最大的三个索引 nsmallest与nlargest相反,求最小 re2 = heapq.nlargest(3, a) #求最大的三个元素 print(list(re1)) #因为re1由map()生成的不是list,直接print不出来,添加list()就行了 print(re2)