[英]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.