Python对列表中的元素进行批量修改


Python编程从入门到实战,编写一个名为make_great() 的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the Great”。
开始使用for循环遍历列表元素,再把“the Great”+原始元素赋值给当前元素,无果。

原始代码:

def make_great(magicians):
    for magician in magicians:
        magician = "the Great " + magician
        print(magician)
    return(magician)
magicians=['dante','vergil','leo']
make_great(magicians)
print(magicians)

运行结果:

the Great dante
the Great vergil
the Great leo
['dante', 'vergil', 'leo']
[Finished in 0.0s]

Python对列表中的元素进行批量修改

发现magicians这个列表并没有被修改。

Why?

我修改了一下代码。
修改代码:

def make_great(magicians):
 n=len(magicians)
 for i in range(0,n):
  magicians[i]="The Great "+magicians[i]
  print(magicians[i])
 return magicians

magicians=['dante','vergil','leo']
make_great(magicians)
print(magicians)

运行结果:

The Great dante
The Great vergil
The Great leo
['The Great dante', 'The Great vergil', 'The Great leo']
[Finished in 0.1s]

Python对列表中的元素进行批量修改

成功了。
WHY?

推测:在原始代码中的for循环里的magician,并不能反向索引列表。所以,执行原始代码块时,只是magician这个临时变量被赋值,列表本身并没有影响。而在修改代码中,代码magicians[i]已经很明确地索引了列表第i-1位置的元素,所以这个修改是直接对该元素生效的。

刚自学Python,谬误之处请指正。

https://www.linuxboy.net/topicnews.aspx?tid=17

linuxboy的RSS地址:https://www.linuxboy.net/rssFeed.aspx

本文永久更新链接地址:https://www.linuxboy.net/Linux/2019-05/158567.htm

相关内容

    暂无相关文章