在python中使用重复迭代器将项插入列表

jes*_*516 1 python iterator repeat

下面的解决方案正在运行,但我想知道代码是否可以改进,或者是否有更有效的方法来实现相同的结果.我需要在列表的开头插入一个"前缀",我使用迭代器来执行此操作.第1行的前缀为"a",第2行的前缀为"b",第3行的前缀为"c",然后第4行的"a"重新启动等.

测试文件:

this,is,line,one
this,is,line,two
this,is,line,three
this,is,line,four
this,is,line,five
this,is,line,six
this,is,line,seven
this,is,line,eight
this,is,line,nine
Run Code Online (Sandbox Code Playgroud)

码:

l = ['a','b','c']
it = iter(l)

with open('C:\\Users\\user\\Documents\\test_my_it.csv', 'rU') as c:
    rows = csv.reader(c)
    for row in rows:
        try:
            i = it.next()
            newrow = [i] + row
        except StopIteration:
            it = iter(l)
            i = it.next()
            newrow = [i] + row
        print(newrow)
Run Code Online (Sandbox Code Playgroud)

结果是:

['a', 'this', 'is', 'line', 'one']
['b', 'this', 'is', 'line', 'two']
['c', 'this', 'is', 'line', 'three']
['a', 'this', 'is', 'line', 'four']
['b', 'this', 'is', 'line', 'five']
['c', 'this', 'is', 'line', 'six']
['a', 'this', 'is', 'line', 'seven']
['b', 'this', 'is', 'line', 'eight']
['c', 'this', 'is', 'line', 'nine']
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 6

这可能会更加简单itertools.cycle,它将l为您无休止地重复:

from itertools import cycle, izip

l = ['a','b','c']

with open('C:\\Users\\user\\Documents\\test_my_it.csv', 'rU') as c:
    rows = csv.reader(c)
    for prefix, row in izip(cycle(l), rows):
        newrow = [prefix] + row
Run Code Online (Sandbox Code Playgroud)