简体   繁体   English

在字典列表中查找最大月份数

[英]Finding the max count of months in a list of dictionaries

I have a list of dictionaries, referenced as city_file, that include several key value pairs.我有一个字典列表,引用为 city_file,其中包含几个键值对。 I am looking to use Counter to find the most common month for the 'Start Time ' key which is provided in '2017-06-01 11:45:35' form.我希望使用Counter来查找以'2017-06-01 11:45:35'形式提供的'Start Time ”键的最常见月份。

How would I go about using datetime to convert the values of 'Start Time' to only return the count of months rather than the full 'Start Time' value and pass that into the Counter (ex: 2017-06-01 11:45:35 as 'January' and gives the total count of January start times).我将如何使用datetime'Start Time'的值转换为仅返回月数而不是完整的'Start Time'值并将其传递给Counter (例如: 2017-06-01 11:45:35作为'January'并给出一月开始时间的总数)。

I have this so far:到目前为止我有这个:

c = Counter((month['Start Time']) for month in city_file)

and it counts each value as unique values for each 'Start Time' rather than counting the number of rides in January.并且它将每个值计算为每个'Start Time'唯一值,而不是计算 1 月份的乘车次数。

input:输入:

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'}
]

expected output:预期输出:

[(January: 2), (February: 1)]

If you only need the month you can extract that part of the string like:如果您只需要月份,您可以提取字符串的那部分,如:

Code:代码:

c = Counter(month['Start Time'][5:7] for month in city_file)

Test Code:测试代码:

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)

Results:结果:

Counter({'June': 2, 'May': 1, 'July': 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM