如何修改数组中的字符串?

时间:2016-06-28 19:11:42

标签: python arrays function

我想创建一个在数组中每个字符串前面添加特定单词的函数。最后我想改变数组。我有这段代码:

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)

此代码不会更改数组。我怎样才能使我的功能发挥作用?

4 个答案:

答案 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)

您可以使用结合magiclambda together

的小型map来完成此操作
>>> magicians = ['hudini', 'angel', 'teller', 'anderson', 'copperfield']
>>> map(lambda el:'pre_'+el,magicians)
['pre_hudini', 'pre_angel', 'pre_teller', 'pre_anderson', 'pre_copperfield']

尝试here