我想创建一个在数组中每个字符串前面添加特定单词的函数。最后我想改变数组。我有这段代码:
def make_great(magicians):
"""Change magicians"""
for magician in magicians:
magician = "the Great" + magician
magicians = ["hudini", "angel", "teller", "anderson", "copperfield"]
make_great(magicians)
print(magicians)
此代码不会更改数组。我怎样才能使我的功能发挥作用?
答案 0 :(得分:12)
您可以使用enumerate
使用索引和值循环遍历列表,然后使用索引将值直接更改为列表:
def make_great(magicians):
for index, magician in enumerate(magicians):
magicians[index] = "the Great " + magician
答案 1 :(得分:4)
enumerate
是最好的事情,然后修改数组中每个索引的值。
for i, magician in enumerate(magicians):
magicians[i] = "the Great " + magician
答案 2 :(得分:4)
当你使用for-each循环时:
def make_great(magicians):
for magician in magicians:
magician = "The Great" + magician
你实际上正在创造一个新的魔术师;所以修改它不会像你找到的那样修改原始数组。
相反,迭代数组中的项目:
def make_great(magicians):
for i in range(len(magicians)):
magicians[i] = "The Great" + magicians[i]
或使用上面提出的枚举器。请参阅:How to modify list entries during for loop?
答案 3 :(得分:1)