python-small-examples

@author jackzhenguo
@desc
@tag
@version 
@date 2020/04/02

195 发现列表前3个最大或最小数

使用堆模块 heapq 里的 nlargest 方法:

import heapq as hq
nums_list = [25, 35, 22, 85, 14, 65, 75, 22, 58]

# Find three largest values
largest_nums = hq.nlargest(3, nums_list)
print(largest_nums)

相应的求最小3个数,使用堆模块 heapq 里的 nsmallest 方法:

import heapq as hq
nums_list = [25, 35, 22, 85, 14, 65, 75, 22, 58]
smallest_nums = hq.nsmallest(3, nums_list)
print("\nThree smallest numbers are:", smallest_nums)
[上一个例子](/python-small-examples/md/194.html) [下一个例子](/python-small-examples/md/196.html)