我有一个字典列表,引用为city_file,包含几个键值对。我希望使用Counter
查找'Start Time
'最常见的月份。密钥以'2017-06-01 11:45:35'
形式提供。
如何使用datetime
将'Start Time'
的值转换为仅返回月数而非完整'Start Time'
值,并将其传递到Counter
(例如:2017-06-01 11:45:35
为'January'
并给出1月份开始时间的总计数。
到目前为止,我有这个:
c = Counter((month['Start Time']) for month in city_file)
并将每个值计为每个'Start Time'
的唯一值,而不是计算1月份的游乐设施数量。
输入:
city_file = [
{'Start Time': '2017-01-01 00:00:36', 'Trip Duration': '356', 'User Type': 'Customer'},
{'Start Time': '2017-01-01 00:00:36', 'Trip Duration': '356', 'User Type': 'Customer'},
{'Start Time': '2017-02-01 00:00:36', 'Trip Duration': '356', 'User Type': 'Customer'}
]
预期产出:
[(January: 2), (February: 1)]
答案 0 :(得分:1)
如果您只需要月份,则可以提取字符串的那一部分,如:
c = Counter(month['Start Time'][5:7] for month in city_file)
import calendar
from collections import Counter
dates = (
'2017-05-01 11:45:35',
'2017-06-01 11:45:35',
'2017-06-01 11:45:35',
'2017-07-01 11:45:35',
)
city_file = [{'Start Time': d} for d in dates]
c = Counter((calendar.month_name[int(month['Start Time'][5:7])] for month in city_file))
print(c)
Counter({'June': 2, 'May': 1, 'July': 1})