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

yipeiwu_com6年前Python基础

一、在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设计】网站的支持!

相关文章

Pytorch 之修改Tensor部分值方式

一:背景引入 对于一张图片,怎样修改局部像素值? 二:利用Tensor方法 比如输入全零tensor,可认为为黑色图片 >>> n=torch.FloatT...

使用Python编写一个模仿CPU工作的程序

今天早上早些时候,在我的Planet Python源中,我读到了一篇有趣的文章"开发CARDIAC:纸板计算机(Developing upwards: CARDIAC: The Card...

sklearn-SVC实现与类参数详解

sklearn-SVC实现与类参数 对应的API:http://scikit-learn.sourceforge.net/stable/modules/generated/sklearn...

用Eclipse写python程序

用Eclipse写python程序

在上一篇文章里已经写过如何安装python和在eclipse中配置python插件,这篇就不多说了,开始入门。 1.先新建一个python工程,File-->New-->Ot...

Python读取mat文件,并转为csv文件的实例

初学Python,遇到需要将mat文件转为csv文件,看了很多博客,最后找到了解决办法,代码如下: #方法1 from pandas import Series,DataFrame...