gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:24:21 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com