遍历嵌套列表并计算元素的平均值

Bri*_*sco 1 python iteration nested-lists

我正在使用 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]]
Run Code Online (Sandbox Code Playgroud)

我正在尝试将其转换为包含商品名称及其平均购买时间的唯一商品列表。

对于此示例,我希望将列表转换为:

['Boots of Speed', 50]
['Health Potion', 70]
['Dorans Blade', 160]
['Dorans Ring', 195]
Run Code Online (Sandbox Code Playgroud)

我尝试的解决方案是创建一个空字典,迭代列表,将字典键设置为项目名称,将平均时间设置为键值。

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
Run Code Online (Sandbox Code Playgroud)

问题是我将尝试在变量dict[item_name]初始化之前对其进行计算。


此时我有点卡住了。任何指示或帮助将不胜感激。

Dan*_*ejo 5

您可以使用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()])
Run Code Online (Sandbox Code Playgroud)

或者作为替代方案,使用collections 模块中的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()])
Run Code Online (Sandbox Code Playgroud)

输出

[['Dorans Blade', 160.0], ['Boots of Speed', 50.0], ['Health Potion', 70.0], ['Dorans Ring', 195.0]]
Run Code Online (Sandbox Code Playgroud)