【问题标题】:Why do I receive a memory error in python for this program?为什么我在 python 中收到此程序的内存错误?
【发布时间】:2019-06-23 21:58:14
【问题描述】:

我是 python 的初学者,正在从事我想要的入门编程项目:

估算一立方英里巧克力冰淇淋的卡路里数量。 注意:一英里有 5,280 英尺,一立方英尺的巧克力冰淇淋含有大约 48,600 卡路里。

我的代码:

Onemile = 5280
cubicmile = 5280**3
calories = 48,600
print("Number of calories per cubic mile:",cubicmile*calories)

输出:

Traceback (most recent call last):

  File "<ipython-input-100-90c2410fa01f>", line 4, in <module>
    print("Number of calories per cubic mile:",cubicmile*calories)

MemoryError

为什么会这样?我构建方程式的方式有问题吗?

【问题讨论】:

  • 请注意,使用逗号是有问题的;没想到会出现内存错误,但您想要卡路里 = 48600
  • calories(48, 600) 的元组,当你将一个元组相乘时,你会得到重复的元组,即 (48, 600, 48, 600, ...) 5280**3 次 - 内存不足。
  • 您可以使用_ 代替逗号来分隔千位(为了便于阅读)。 calories = 48_600

标签: python function math arithmetic-expressions


【解决方案1】:

如前所述,问题在于calories = 48,600 这一行。

问题在于,由于右侧的,,这与calories = (48, 600)相同,即tuple。对于元组,乘法意味着“重复元组n 次”。所以例如2 * (48, 600) == (48, 600, 48, 600).

但是既然你做了5280**3 * calories,这是试图分配一个带有2 * 5280**3 = 294395904000元素的元组,这似乎太大而无法放入你的内存(假设每个值64位,这将是2.14 TiB,更大比大多数人的记忆)。

请注意,在Python 3.6+ 中,您可以使用_ 作为千位分隔符:

calories = 48_600

【讨论】:

    【解决方案2】:

    您正在尝试打印元组 (48, 600)(这就是您在编写 calories = 48,600 时得到的)147197952000 次。

    你的输出是:

    Number of calories per cubic mile: (48, 600, 48, 600, 48, 600, ... , 48, 600)
    

    您的电脑根本无法处理大约。 1324781568000 要立即转储的字符。

    不要使用, 作为千位分隔符,您应该只写48600

    Onemile = 5280
    cubicmile = 5280**3
    calories = 48600
    print("Number of calories per cubic mile:",cubicmile*calories)
    

    输出:

    Number of calories per cubic mile: 7153820467200000
    

    编辑:

    实际上,失败的不是打印或创建如此大的字符串,因为它似乎 - 至少对我来说 - 当尝试创建指向元组的 147197952000 指针时,Python 会耗尽内存,你可以只运行(48,600) * 147197952000进行测试。

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 2016-12-27
      • 2012-09-15
      • 1970-01-01
      • 2019-11-22
      相关资源
      最近更新 更多