如何制作循环:
for i, line in enumerate(lines_f1, start = 0):
从1(i = 1)开始计数,并在每次迭代中递增2?
答案 0 :(得分:2)
只需进行常规枚举(0,1,2,3等),然后用它来计算你想要的数字:
>>> lines_f1 = ['line1', 'line2', 'line3', 'line4', 'line5']
>>> for i, line in enumerate(lines_f1, start = 0):
... i = 1 + i*2
... print i, line
...
1 line1
3 line2
5 line3
7 line4
9 line5
答案 1 :(得分:1)
好吧,如果你想从1开始,从1开始:
enumerate(lines_f1, start = 1)
如果你想跳过其他所有行:
import itertools
for i,l in itertools.islice(enumerate(lines_f1, start = 1),0,None,2):
pass #whatever you want here
如果您只想在ieach迭代中使用两次i
进行编号,只需乘以:
for i,l in enumerate(lines_f1, start = 1):
linenum = 2*i
答案 2 :(得分:0)
不确定您想要的输出是什么,但是:
lines_f1 = ["a",'b','c','d','e','f']
print range(1,len(lines_f1),2), lines_f1[1::2]
收率:
[1,3,5] ['b','d','f']
答案 3 :(得分:0)
使用itertools函数来避免构建不必要的单独列表。
如果您要“增加2”,则不清楚是要跳过行还是仅增加i
。如果你想跳过线,请使用Marcin的答案。否则,请尝试:
for i, line in itertools.izip(itertools.count(1, 2), lines_f1):