【问题标题】:Why is this dictionary comprehension generating the same value for all keys? [duplicate]为什么这个字典理解会为所有键生成相同的值? [复制]
【发布时间】: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


【解决方案1】:

您不需要在字典推导中创建三重 for 循环

profit_dict = {show: (((revenue[i] - budget[i]) / budget[i]) * 100) for i, show in enumerate(top5shows)}
print(profit_dict) # {'Soldier': 10.0, 'The Run': 72.72727272727273, 'Metachomas': 135.29411764705884, 'The Average Lad': 14.999999999999991, 'James Eathersen': 100.0}

【讨论】:

  • 解决了!谢谢!
【解决方案2】:

假设您想并行迭代列表而不是嵌套(就像您的代码一样),一个可行的解决方案将如下所示:

profit_dict = {show: (((revenue[idx] - budget[idx]) / budget[idx]) * 100) for idx, show in enumerate(top5shows)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2021-11-03
    • 2022-01-23
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多