Skip to main content
 首页 » 编程设计

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

2025年05月04日13JustinYoung

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

请您参考如下方法:

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