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

最佳答案

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

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),依此类推,直到耗尽内存。

09-05 01:27