如果一本字典里的条目是蓝莓,我该如何找到它们的平均价格呢?

2024-06-16 15:07:02 发布

您现在位置:Python中文网/ 问答频道 /正文

使用下一个单元格中定义的字典price来回答问题。在下一个单元格中,使用for循环计算并打印蓝莓的平均价格

price = {
1: ['Blueberry', 'US', 1.31],
2: ['Pineapples', 'Brazil', 3.71],
3: ['Pear', 'Costa Rica' , 0.58],
4: ['Plum', 'US', 1.00],
5: ['Grapes', 'US', 1.25],
6: ['Papaya', 'Costa Rica', 0.4 ],
7: ['Blueberry', 'Mexico' , 1.58],
8: ['Plum', 'Mexico', 1.50],
9: ['Grapes', 'Italy', 2.25],
10: ['Blueberry', 'Italy', 2.50 ]
}

我需要得到蓝莓的平均价格,但我不知道只有蓝莓的价格是多少


Tags: for字典定义priceus蓝莓blueberrymexico
2条回答

如果这是一次性的,你可以写一些东西,比如

blueberry_prices = [v[2] for v in price.values() if v[0] == "Blueberry"]
avg_blueberry_price = sum(blueberry_prices) / len(blueberry_prices)

它使用列表理解(从字典中的值)只提取名称(列表索引0)等于“blueberry”的价格(列表索引2)

对于更频繁地执行此操作的任何操作,您可能希望编写一个与输入进行比较的通用函数,而不是“blueberry”

请尝试以下代码。希望这有助于:

price = {
1: ['Blueberry', 'US', 1.31],
2: ['Pineapples', 'Brazil', 3.71],
3: ['Pear', 'Costa Rica' , 0.58],
4: ['Plum', 'US', 1.00],
5: ['Grapes', 'US', 1.25],
6: ['Papaya', 'Costa Rica', 0.4 ],
7: ['Blueberry', 'Mexico' , 1.58],
8: ['Plum', 'Mexico', 1.50],
9: ['Grapes', 'Italy', 2.25],
10: ['Blueberry', 'Italy', 2.50 ]
}


average = [ value[2] for key, value in price.items() if value[0]=='Blueberry']

print(sum(average)/len(average))

输出为:

1.7966666666666669

相关问题 更多 >