![](/img/trans.png)
[英]creating a dictionary from 2 list one as key other as value in python
[英]Using python, creating a dictionary by extracting key:value from a list
list1 = [['8/16/2016 9:55', 6], ['11/22/2015 13:43', 29], ['5/2/2016 10:14', 1],
['8/2/2016 14:20', 3], ['10/15/2015 16:38', 17], ['9/26/2015 23:23', 1],
['4/22/2016 12:24', 4], ['11/16/2015 9:22', 1], ['2/24/2016 17:57', 1],
['6/4/2016 17:17', 2]]
count_by_hour = {} # this is created by extracting the hour from index[0] of list1
for each in list1:
if each[0].split(':')[0][-2] == " ": #split by : to get second last char and check if >9
hours.append(each[0].split(':')[0][-1:]) # if hour is <9 take last char which is hour
else:
hours.append(each[0].split(':')[0][-2:]) #else take last 2 chars
print('Hour extracted:')
print(hours)
輸出:
Counts by hour:
{'9': 2, '13': 1, '10': 1, '14': 1, '16': 1, '23': 1, '12': 1, '17': 2}
現在,我該如何執行以下操作:
comments_by_hour = {}
Expected Outcome:
{9:7, 13:29, 10:1, 14:3, 16:17, 23:1, 12:4, 17:2} #value is a total for every hour that exists as a key in list1
與往常一樣,任何幫助表示贊賞。
請注意,我們需要為許多類別(小時)中的每一個單獨累加總和。 一個簡單的解決方案(在純 Python 中)結合了累加器模式,同時使用字典來存儲所有計數。
首先,讓我們使用time.strptime
使用列表time.strptime
來提取小時數。
In [1]: list1 = [['8/16/2016 9:55', 6], ['11/22/2015 13:43', 29], ['5/2/2016 10:14', 1],
: ['8/2/2016 14:20', 3], ['10/15/2015 16:38', 17], ['9/26/2015 23:23', 1],
: ['4/22/2016 12:24', 4], ['11/16/2015 9:22', 1], ['2/24/2016 17:57', 1],
: ['6/4/2016 17:17', 2]]
In [2]: from time import strptime
In [3]: hour_list = [(strptime(time, "%m/%d/%Y %H:%M").tm_hour, val) for time, val in list1]
解決方案是使用字典來累積每個類別的統計信息。 通過(a)從一個空字典開始並(b)更新每個新值的總和來做到這一點。 這可以如下完成。
In [4]: comments_by_hour = {}
In [5]: for hour, val in hour_list:
: comments_by_hour[hour] = val + comments_by_hour.get(hour, 0)
:
In [6]: comments_by_hour
Out[6]: {9: 7, 13: 29, 10: 1, 14: 3, 16: 17, 23: 1, 12: 4, 17: 3}
請注意, comments_by_hour.get(hour, 0)
用於獲取該小時的當前值(如果存在),否則使用默認值 0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.