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

标签 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

代码:

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

关于python - 在 python 中使用重复迭代器将项目插入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31944608/

相关文章:

python - 大部件的矢量幅度

python - 将变量转换为字典

c# - yield 语句实现

c++ - 为什么 'std::tie' d 对象的结构化绑定(bind)失败?

python - 计算python中分布的矩(均值,方差)

c++ - 为什么迭代器需要 CopyConstructible 和 CopyAssignable?

css - 3个div作为背景

perl - 嵌套循环 - 为什么循环包含先前的计算?

vim - 如何在 Vim 中重复任何命令,例如 emacs 中的 "C-x z"?

Python Tika 无法从 url 解析 pdf