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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

白云深秋   2021-03-30 我要评论

一、在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值的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们