我正在使用 Riot 的 API 开发一个应用程序来分析玩家英雄联盟比赛历史的数据。
我有一个列表,其中包含商品名称,以及购买时间(以秒为单位)
item_list =
[['Boots of Speed', 50],
['Health Potion', 60],
['Health Potion', 80],
['Dorans Blade', 120],
['Dorans Ring', 180],
['Dorans Blade', 200],
['Dorans Ring', 210]]
我正在尝试将其转换为包含项目名称 和平均购买时间 的项目唯一列表。
对于这个例子,这就是我希望将我的列表转换成:
['Boots of Speed', 50]
['Health Potion', 70]
['Dorans Blade', 160]
['Dorans Ring', 195]
我尝试过的解决方案是创建一个空字典,遍历列表,将字典键设置为项目名称,将平均时间设置为键值。
dict = {}
for item in item_list:
item_name = item[0]
time_of_purchase = item[1]
dict[item_name] = (dict[item_name] + time_of_purchase) / 2 # Would cast this as an integer
这个问题是我将尝试在变量 dict[item_name] 初始化之前对其进行计算。
此时我有点卡住了。任何指点或帮助将不胜感激。
请您参考如下方法:
你可以使用 setdefault :
item_list = [['Boots of Speed', 50],
['Health Potion', 60],
['Health Potion', 80],
['Dorans Blade', 120],
['Dorans Ring', 180],
['Dorans Blade', 200],
['Dorans Ring', 210]]
result = {}
for item, count in item_list:
result.setdefault(item, []).append(count)
print([[key, sum(value) / len(value) ] for key, value in result.items()])
或者作为替代使用 defaultdict来自收藏模块:
from collections import defaultdict
item_list = [['Boots of Speed', 50],
['Health Potion', 60],
['Health Potion', 80],
['Dorans Blade', 120],
['Dorans Ring', 180],
['Dorans Blade', 200],
['Dorans Ring', 210]]
result = defaultdict(list)
for item, count in item_list:
result[item].append(count)
print([[key, sum(value) / len(value) ] for key, value in result.items()])
输出
[['Dorans Blade', 160.0], ['Boots of Speed', 50.0], ['Health Potion', 70.0], ['Dorans Ring', 195.0]]
