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)
有人可以解释代码
c = Counter((calendar.month_name[int(month['Start Time'][5:7])] for month in city_file))
特别是部分,如果我输入5:7以外的任何东西,它会给出错误信息。
month['Start Time][5:7]
期望的输出:
数月的例子1月12日12月13日
那你可以一步一步评估:
[d[5:7] for d in dates] #extract month from date string
#['05', '06', '06', '07']
[int(d[5:7]) for d in dates] #extract month from date string and convert to int
#[5, 6, 6, 7]
calendar.month_name[:] #get all month names
['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
[calendar.month_name[int(d[5:7])] for d in dates] #get month names that match month in dates
#['May', 'June', 'June', 'July']
一旦你弄清楚这个流程,你需要看看Counter。
Start Time
包含dates
值。
给定格式yyyy-mm-dd hh:mm:ss
,范围[5:7]
是月值。
您的月份变量是字典。通过使用month['Start Time']
,您将使用'Start Time'
键访问字典并返回您的时间字符串。 [5:7]
部分正在切割从month['Start Time]
中获取的字符串,该字符串从索引5开始并在索引7之前结束。这[5:7]与字符串的月份相关。然后,您将获取月份的字符串并将其转换为整数:int(month['Start Time'][5:7])
。然后你有另一个对象calendar.month_name
,它给出了传递给它的密钥的月份名称。你在month
的每个city_file
都这样做。这会创建一个生成器对象(您可以将其视为列表)并将其传递给Counter对象。然后Counter对象从生成器获取所有值并计算它们出现的次数。