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

Use repeating iterator in python to insert item into list

下面的解决方案有效,但我想知道是否可以改进代码,或者是否有更有效的方法来实现相同的结果。我需要在我的列表的开头插入一个 "prefix" 并且我正在使用迭代器来这样做。第 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

代码:

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)

结果是:

['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']

只需循环列表 l 使用 itertools.cycle, zipping the cycle object and your rows with itertools.izip:

from itertools import cycle, izip

l = ['a','b','c']
it = iter(l)
import csv
with open('in.csv', 'rU') as c:
    rows = csv.reader(c)
    for a, row in izip(cycle(l), rows):
        print([a]+ row)

输出:

['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']

使用 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