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

时间:2015-08-11 14:30:42

标签: python iterator repeat

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

测试文件:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

只需使用itertools.cycle循环列表l,使用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']