如何在列表中获取python中当前循环的内部索引?

and*_*dio 2 python indexing counter loops

我有一个 listx =[1,2,3,4,5,6,7,8,9]

我想改变列表中的每个第N项.例如,我想修改每2个项目步骤,假设我想修改+1.所以我想得到结果=[1+1,2,3+1,4,5+1,6,7+1,8,9+1] =[2,2,4,4,6,6,8,8,9]

我可以通过使用for循环,通过添加计数器变量,然后通过计数器%2 == 0检查计数器.但这次我只是好奇使用单行声明.这就是我想要的=

newlistx=[i+1 for i in listx] < - 这会修改所有项目,所以我希望我可以在这个迭代过程中使用一些内部索引,变成这样:

newlistx=[i+1 if (__indexing__%step==0) else i for i in listx] 其中step = 2.

实际上,我可以使用list.index()函数,如下所示:

newlistx=[i+1 if listx.index(i)%2==0 else i for i in listx]

这个问题只有在所有项目都是唯一的情况下才有效,如果我得到的项目具有相同的值,那么index()将返回错误的值.

再次,我只是好奇我是否可以获取一些内部索引或计数器,如果存在的话.

Die*_*Epp 7

你可以使用这个enumerate功能.

newlist = [x + 1 if n % step == 0 else x
           for (n, x) in enumerate(oldlist)]
Run Code Online (Sandbox Code Playgroud)

该enumerate函数迭代序列并生成带有索引的对象.