我正在处理一个不规则结构的文本文件,它由一个头和不同部分的数据组成。我的目标是遍历一个列表并在遇到某个角色时跳到下一个部分。我在下面举了一个简单的例子。处理这个问题的优雅方法是什么?

lines = ['a','b','c','$', 1, 2, 3]

for line in lines:
    if line == '$':
        print("FOUND END OF HEADER")
        break
    else:
        print("Reading letters")

# Here, I start again, but I would like to continue with the actual
# state of the iterator, in order to only read the remaining elements.
for line in lines:
    print("Reading numbers")

最佳答案

通过在for循环之外使用内置函数iter创建行迭代器,实际上可以为两个循环创建一个迭代器。这样,它将在第一个循环中部分耗尽,并在下一个循环中重用。

lines = ['a','b','c','$', 1, 2, 3]

iter_lines = iter(lines) # This creates and iterator on lines

for line in iter_lines :
    if line == '$':
        print("FOUND END OF HEADER")
        break
    else:
        print("Reading letters")

for line in iter_lines:
    print("Reading numbers")

上面打印了这个结果。
Reading letters
Reading letters
Reading letters
FOUND END OF HEADER
Reading numbers
Reading numbers
Reading numbers

10-08 13:09