使用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()])


或者,可以使用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()])


输出量

[['Dorans Blade', 160.0], ['Boots of Speed', 50.0], ['Health Potion', 70.0], ['Dorans Ring', 195.0]]

关于python - 遍历嵌套列表并计算元素的平均值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52939786/

10-12 00:44
查看更多