python - 使用 for 循环 append 到列表时出现 MemoryError

标签 python list for-loop append

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)

为什么第二个功能不起作用?我试图将名单中的每个魔术师更改为“[魔术师]伟大”,但我不断收到内存错误。有什么建议吗?

谢谢你, -困惑的n00b

最佳答案

您不应该追加到列表中,您应该将每个元素替换为其“伟大”版本。

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

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

关于python - 使用 for 循环 append 到列表时出现 MemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58720228/

相关文章:

python - 在 celery 工作人员内部存储数据的常见且明显的方式是什么?

arrays - Kotlin - 在数组中查找匹配的对象

python - 如何从python中的列表中获取最常见的元素

c - 为什么我的小C循环不能正确打印到帧缓冲区,但是展开的版本可以打印?

c++ - for循环中使用的位操作

c# - 如何继续将整数添加到列表中,同时查看这些整数是否已经在列表中?

python - 无法在 unicode 中打印某些上标

python - 如何检查小写字母是否存在?

python - TypeError - 无法将 'int' 对象隐式转换为 str

python - 如何用for循环影响列表的显示?