簡體   English   中英

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

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

我有一個字典列表,引用為 city_file,其中包含幾個鍵值對。 我希望使用Counter來查找以'2017-06-01 11:45:35'形式提供的'Start Time ”鍵的最常見月份。

我將如何使用datetime'Start Time'的值轉換為僅返回月數而不是完整的'Start Time'值並將其傳遞給Counter (例如: 2017-06-01 11:45:35作為'January'並給出一月開始時間的總數)。

到目前為止我有這個:

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)]

如果您只需要月份,您可以提取字符串的那部分,如:

代碼:

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})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM