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

在python中使用重复迭代器将项插入列表,python,iterator,repeat,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

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

结果如下:

['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
,压缩循环对象和行:

输出:

['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
,压缩循环对象和行:

输出:

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

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

这可能会简单得多,它将为您处理无休止重复的
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

“下面的解决方案是可行的,但我想知道代码是否可以改进,或者是否有更有效的方法来实现相同的结果。”-这是一个好迹象,表明您最好发布,通读“如何询问”页面,看看它是否与此相关。“下面的解决方案是可行的,但我想知道代码是否可以改进,或者是否有更有效的方法来实现相同的结果。“-这是一个好迹象,表明你最好在上面发帖,通读“如何提问”页面,看看它是否与此相关。@Padraiccningham人们已经说过-他们更喜欢小狗而不是酒!它是不含酒精的,不像我昨晚喝的酒精含量很高的酒@帕德雷坎宁厄姆:很明显,至少你已经说服了OP;o) @PadraicCunningham人们已经说过了——他们更喜欢小狗而不是酒!它是不含酒精的,不像我昨晚喝的酒精含量很高的酒@帕德雷坎宁厄姆:很明显,至少你已经说服了OP;o)