Python--修改列表中所有的元素

此段代码循环了列表中的值 但是不会修改列表

// An highlighted block
def make_great(magicians):
    for magician in magicians:
    #每次循环拿到列表的的值进行赋值给magician
        magician = "the Great " + magician
        #打印出magician的的值,应为 "the Great " + magician
        print(magician)
        #因为magician他只是变量,每次循环也只是修改的是变量中的值而不是列表
    return(magician)
magicians=['dante','vergil','leo']
print(make_great(magicians)) #此时的打印结果是方法return返回的值,并不是列表的
print(magicians)

》》》
the Great dante #第一次循环时magician的值为"the Great " +magician
the Great vergil#第二次
the Great leo #第三次
['dante', 'vergil', 'leo'] #原始列表中的值未被改变

修改后

def make_great(magicians):
	n=len(magicians) #拿到列表的长度进行循环
	for i in range(0,n):
	#下面这行代码才是真正意义上的修改列表
		magicians[i]="The Great "+magicians[i]
		#i列表的为下标,列表中为i下标的元素被修改
		print(magicians[i])
	return magicians
》》》》》》》》》》》》
结果如下
the Great dante
the Great vergil
the Great leo
['the Great dante', 'the Great vergil', 'the Great leo']
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值