Python使用for循环修改列表内的元素,列表并没有变化

目标:

将列表 magicians 中的每个人名前加上“the Great”

原代码为:

magicians=['LiHua','Xiaogang','Hanmeimei']
def show_magicians(magicians):
    print(magicians)
show_magicians(magicians)

#在每个魔术师名字前加the Great
def make_great(magicians):
    for magician in magicians:
        magician="the Great "+magician
    print(magicians)
make_great(magicians)

输出不符合预期:

['LiHua', 'Xiaogang', 'Hanmeimei']
['LiHua', 'Xiaogang', 'Hanmeimei']

修改make_great(magicians)函数,如下代码后成功

magicians=['LiHua','Xiaogang','Hanmeimei']
def show_magicians(magicians):
    print(magicians)
show_magicians(magicians)

#在每个魔术师名字前加the Great
def make_great(magicians) :
    length=len(magicians)
    for a in range(1,length+1) :
        magicians[a-1]='the Great '+magicians[a-1]
    print(magicians)
make_great(magicians)

输出结果为:

['LiHua', 'Xiaogang', 'Hanmeimei']
['the Great LiHua', 'the Great Xiaogang', 'the Great Hanmeimei']

出现这种情况的原因:

原代码中,for magician in magicians 对列表中的每个元素进行赋值,之后,没有将改变了的元素再放入原来的magicians中,所以列表没有变化。

你可能感兴趣的:(Python学习)