I have a list of objects representing widgets. Each widget object has a manufactured DateTime field that holds the date and time when the widget was made. All the widgets in the list were manufactured in a particular year.
I would like to get a list with the total widgets manufactured each month - e.g.:
>>> totals
[1, 5, 819, 187, 1, 5, 15, 9, 13, 77, 54, 22]
So in the above list there were 819 widgets made in M开发者_如何学运维arch.
What's a pythonic way of doing this?
totals = [0] * 12
for widget in widgets:
totals[widget.datetime.month - 1] += 1
The indices of totals
are in the range 0 to 11, while months usually are in the range 1 to 12, so we need the - 1
.
An alternative in Python 2.7 or 3.1 or above:
from collections import Counter
totals = Counter(widget.datetime.month for widget in widgets)
[sum(1 for widget in widgets if widget.datetime.month == m) for m in range(1,13)]
精彩评论