【问题标题】:Getting MemoryError when appending to a list using a for loop使用 for 循环附加到列表时出现 MemoryError
【发布时间】:2020-03-02 08:26:11
【问题描述】:
def show_magicians(magicians_list):
    """Print the name of each magician in a list."""
    for magician in magicians_list:
        print(magician.title())

def make_great(magicians_list):
    """Make each magician great again."""
    for magician in magicians_list:
        magician = magician + " " + "the Great"
        magicians_list.append(magician)

list_of_dudes = ['houdini','david blaine','jebus']

make_great(list_of_dudes)

show_magicians(list_of_dudes)

print(list_of_dudes)

为什么第二个功能不起作用?我正在尝试将帅哥列表中的每个魔术师更改为“[Magician] the Great”,但我不断收到内存错误。有什么建议吗?

谢谢你, -困惑的n00b

【问题讨论】:

  • 您在迭代列表时附加到列表,因此它本质上是一个无限循环。
  • 您可以将 make_great 方法替换为 magicians_list = [m + " the Great" for m in magicians_list] 之类的方法

标签: python list for-loop append


【解决方案1】:

你不应该追加到列表中,你应该用它的“伟大”版本替换每个元素。

def make_great(magicians_list):
    """Make each magician great again."""
    for i, magician in enumerate(magicians_list):
        magician = magician + " " + "the Great"
        magicians_list[i] = magician

您的版本正在附加到它正在迭代的列表中。结果,它永远不会结束,因为它会继续迭代新元素,并使它们变得更大 (houdini the Great the Great),然后迭代这些元素 (houdini the Great the Great the Great),依此类推,直到内存不足。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-23
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多