【发布时间】:2019-07-25 10:01:30
【问题描述】:
所以我是 Python 新手,并试图从两个列表中生成以下字典推导。
top5shows = ['Soldier','The Run', 'Metachomas','The Average Lad','James Eathersen']
budget = [200, 110, 34, 2, 0.5]
revenue = [220,190, 80, 2.3, 1]
profit_dict = {show: (((rev - bud) / bud) * 100) for show in top5shows for rev in revenue for bud in budget}`
这个想法是生成一个以电影名称为键的字典,以利润百分比为值。但是,结果是所有键的值都相同,即列表中最后一部电影的利润百分比。
结果:
{'Soldier': 100.0, 'The Run': 100.0, 'Metachomas': 100.0, 'The Average Lad': 100.0, 'James Eathersen': 100.0}
【问题讨论】:
-
但是我在哪里为字典提供重复的键?
-
您有三个嵌套的
for循环 - 即您正在为每个顶级节目迭代每一对可能的(budget, revenue);您可能想遍历 parallel 中的三个列表。 -
哦,可能!如何在字典理解中做到这一点?还是可以在 dict comp 中做到这一点?
标签: python dictionary dictionary-comprehension