网络编程
位置:首页>> 网络编程>> Python编程>> Python在for循环中更改list值的方法【推荐】

Python在for循环中更改list值的方法【推荐】

作者:白云深秋  发布时间:2023-03-05 07:14:28 

标签:python,for,循环,list

一、在for循环中直接更改列表中元素的值不会起作用:

如:


l = list(range(10)[::2])
print (l)
for n in l:
n = 0
print (l)

运行结果:

[0, 2, 4, 6, 8]
[0, 2, 4, 6, 8]

l中的元素并没有被修改

二、在for循环中更改list值的方法:

1.使用range


l = list(range(10)[::2])
print (l)
for i in range(len(l)):
l[i] = 0
print (l)

运行结果:

[0, 2, 4, 6, 8]
[0, 0, 0, 0, 0]

2.使用enumerate


l = list(range(10)[::2])
print (l)
for index,value in enumerate(l):
l[index] = 0
print (l)

运行结果:

[0, 2, 4, 6, 8]
[0, 0, 0, 0, 0]

总结

以上所述是小编给大家介绍的Python在for循环中更改list值的方法网站的支持!

来源:https://www.cnblogs.com/lichuang/archive/2018/08/17/9492821.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com