获取列表中的最大的N项和最小的N项
#!/sur/bin/env python
# -*- coding:utf-8 -*-
# author:zengsf
#time:2018/10/31 import heapq nums = [1, 0, 2, 29, 7, -7, 18, 23, 5, 20, 9, 10, 12] # 最大的4个数的索引
max_num_index_list = map(nums.index, heapq.nlargest(4, nums)) # 最小的4个数的索引
min_num_index_list = map(nums.index, heapq.nsmallest(4, nums)) print(max_num_index_list)
print(list(max_num_index_list))
print(list(min_num_index_list))
输出结果:
<map object at 0x0000021066E627F0>
[3, 7, 9, 6]
[5, 1, 0, 2]