擅长:python、mysql、java
<p>我会先填写字典,对于每个<code>item_name</code>,我会有一个<code>time_of_purchase</code>值的列表。一旦完成,我将遍历字典(键,列表)对,并计算每个列表的平均值。你知道吗</p>
<pre><code>item_list = [['Boots of Speed', 50],
['Health Potion', 60],
['Health Potion', 80],
['Dorans Blade', 120],
['Dorans Ring', 180],
['Dorans Blade', 200],
['Dorans Ring', 210]]
# Fill the dictionary
d = {}
for item in item_list:
item_name, time_of_purchase = item
if item_name not in d:
d[item_name] = []
d[item_name].append(time_of_purchase)
# Now calculate and print the average
retlist = []
for item_name, list_of_times in d.items():
new_entry = [
item_name,
sum(list_of_times) // len(list_of_times),
]
retlist.append(new_entry)
print retlist
</code></pre>
<p>丹尼尔的解决方案也是如此,以一种更具Python性和效率的方式。你知道吗</p>