您的位置:首页 > 博客中心 > 编程语言 >

关于Python修改列表的值的问题

时间:2022-03-28 15:43

由于惯性思维,导致使用for循环修改列表中的值出现问题

首次尝试:

    

def make_great(original):
    for magician in original:
        magician = "the Great " + magician


magicians = ["david", "tom", "jimmy"]
make_great(magicians)
show_magicians(magicians)

运行结果:技术图片

 

 

显然列表中的值并没有改变。

思考:for语句定义一个变量进行遍历,但只是访问当前值。操作列表中的值正确方法是使用下标。

修改后:

def make_great(original):
    j = len(original)
    for i in range(0, j):
        original[i] = "the Great " + original[i]

运行结果:技术图片

 

本类排行

今日推荐

热门手游