gpt4 book ai didi

python - 使用 Python 循环遍历文件时如何提前读取文件?

转载 作者:太空狗 更新时间:2023-10-29 22:20:06 24 4
gpt4 key购买 nike

我正在遍历一个文件,如果我找到了一些东西,我想在将控制权返回到主循环之前提前阅读几行以寻找一些东西。但是,我想在我停止向前看的那一刻恢复控制。

示例代码:

for line in file:
line = line.strip()
llist = line.split()

if llist[0] == 'NUMS':
# some loop to read ahead and print nums on their own line
# until it finds END, then return control to the main for
# loop at the point where it stopped looking ahead.

示例输入:

NUMS
1
2
3
4
5
END
SOME
MORE
STUFF
NUMS
6
7
8
9
0
END

期望的输出:

1 2 3 4 5
6 7 8 9 0

我是 Python 的新手,所以如果除了使用循环进行前瞻之外还有更好的方法来做到这一点,我很高兴看到它。

最佳答案

如无必要,提前阅读并不是一个好主意,这里就是这种情况。通过维护一位状态,您需要做的事情可以在单个 for 循环中完成。这允许错误检查,并且扩展到比同一迭代器上的嵌套循环可以处理的复杂得多的要求

guff = """NUMS
1
2
etc etc
9
0
END"""

state = ""
for item in guff.split():
if item == "NUMS":
if state == "NUMS": print "missing END"
state = "NUMS"
elif item == "END":
if state == "": print "missing NUMS"
state = ""
print
elif state == "NUMS":
print item,

if state == "NUMS": print # missing END

关于python - 使用 Python 循环遍历文件时如何提前读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8189982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com