一些好用的python模块

calendar: 显示指定月份的天数

heapq: 利用堆的特性,实现数据的排序

calendar

每个月份的天数是不一样的,像1,3,5等月份有31天,4,6,9等月份有30天,更别说,天数更为特殊的2月份.

所以如何快速有效的获取某年某月的总天数,就比较麻烦了.Python为我们提供了内置的模块来解决这个问题.

import calendar
print(calendar.monthrange(2019,2)[1])   # 28
print(calendar.monthrange(2008,2)[1])   # 29

 

heapq

当我们想从一个集合中获取最大或者最小的N个元素时,这个模块就很方便了.

importheapq
nums= [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]

也能接收一个关键字参数,用于更复杂的数据结构中:

例如: 根据 'price' 进行排序

portfolio = [
 {'name': 'IBM', 'shares': 100, 'price': 91.1},
 {'name': 'AAPL', 'shares': 50, 'price': 543.22},
 {'name': 'FB', 'shares': 200, 'price': 21.09},
 {'name': 'HPQ', 'shares': 35, 'price': 31.75},
 {'name': 'YHOO', 'shares': 45, 'price': 16.35},
 {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap =heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive =heapq.nlargest(3, portfolio, key=lambda s: s['price'])

堆数据结构最重要的特性是,heapq[0] 永远是最小的元素, heapq.heappop() 会将第一个元素弹出,然后用下一个最小的元素来取代被弹出的元素. 因此,如果想要查出最小的3个元素,也可以用这种方式:

>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> import heapq
>>> heapq.heapify(nums)
>>> nums
[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
>>>
>>> heapq.heappop(nums)
-4
>>> heapq.heappop(nums)
1
>>> heapq.heappop(nums)
2

 

posted @ 2019-08-01 16:15  yara-ning  阅读(463)  评论(0编辑  收藏  举报