【问题标题】:Calculate the average budget of all movies in the data set [closed]计算数据集中所有电影的平均预算 [关闭]
【发布时间】:2021-05-24 14:59:58
【问题描述】:
movies = [
     ("Titanic", 20000000),
     ("Dracula", 9000000),
     ("James Bond", 4500000),
     ("Pirates of the Caribbean: On Stranger Tides", 379000000),
     ("Avengers: Age of Ultron", 365000000),
     ("Avengers: Endgame", 356000000),
     ("Incredibles 2", 200000000)
 ]

想要计算数据集中所有电影的平均预算。 有什么建议吗?

【问题讨论】:

  • 你试过什么?基本算法应该是:创建新变量来保存总数,然后执行 for/while 循环,最后将总数除以元素数
  • 将所有电影预算相加并除以电影数量。有什么困难?
  • @JohnGordon 我收到 TypeError: 'int' object is not iterable

标签: python python-3.x


【解决方案1】:

您可以使用 accumulator 变量来保存总和和 for 循环:

这是一个例子:

movies = [
    ("Titanic", 20000000),
    ("Dracula", 9000000),
    ("James Bond", 4500000),
    ("Pirates of the Caribbean: On Stranger Tides", 379000000),
    ("Avengers: Age of Ultron", 365000000),
    ("Avengers: Endgame", 356000000),
    ("Incredibles 2", 200000000)
]

if __name__ == "__main__":
    # Declarative
    accumulator = 0
    for (_, budget) in movies:
        accumulator += budget
    print(accumulator / len(movies))

for 语句中,我将元组中的两个项目解包为两个新变量:_budget。使用_ 是声明您不需要使用该变量的常见做法。

最后一行打印平均值,计算方法是除以列表的长度。

【讨论】:

  • 感谢它的工作。你能解释一下 if 部分吗?
  • 当然。我们可以使用if __name__ == "__main__" 块来允许或阻止在导入模块时运行部分代码。 if 代码块只有在你使用 python 调用模块时才会运行,但如果你从另一个模块导入它则不会运行。
【解决方案2】:

假设movies 是一个普通的 Python 列表,并且您希望获得以 美元 为单位的平均成本:

movies = [
     ("Titanic", 20000000),
     ("Dracula", 9000000),
     ("James Bond", 4500000),
     ("Pirates of the Caribbean: On Stranger Tides", 379000000),
     ("Avengers: Age of Ultron", 365000000),
     ("Avengers: Endgame", 356000000),
     ("Incredibles 2", 200000000)
 ]

totalCost = 0
totalMovies = 0

for movie, price in movies:
    totalCost += price
    totalMovies +=1
    
print (f"The average cost per movie is {totalCost/totalMovies:.2f}$")

{totalCost/totalMovies:.2f} 行在选择两个十进制值 (.2f) 时使用 Python F strings 插入计算内联

希望一切都清楚!

【讨论】:

    【解决方案3】:

    计算平均值的常规方法在这里适用。类似于

    total = 0
    for movie, budget in movies:
      total += budget
    
    average = total / movies.length
    

    应该在这里为您解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2021-07-05
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多