Python在for循环中更改list值的方法【推荐】
2019/7/15 0:23:59
本文主要是介绍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值的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!
这篇关于Python在for循环中更改list值的方法【推荐】的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python