如何使用缓冲区迭代字符串(python)
我试图找到一些代码,给定一个字符串,允许我使用 for 循环构造迭代每一行,但附加的要求是单独的 for 循环构造不会将迭代重置回开头。
目前我已经
sList = [line for line in theString.split(os.linesep)]
for line in SList
... do stuff
但是连续的 for 循环会将迭代重置回开始。
python 中是否存在用于此目的的东西,或者我必须从头开始编写一个?
I'm trying to find some code that, given a string, will allow me to iterate over each line using the for loop construct, but with the added requirement that separate for loop constructs will not reset the iteration back to the beginning.
At the moment I have
sList = [line for line in theString.split(os.linesep)]
for line in SList
... do stuff
But successive for loops will reset the iteration back to the beginning.
Does something in python exist for this, or will I have to write one from scratch?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需使用生成器表达式(genexp)而不是您现在使用的列表理解(listcomp) - 即:
仅此而已 - 如果您对代码感到满意(按 os.linesep 分割,即使普通文本 I/ Python 中的 O 已经将它们翻译成
\n
...),您所需要做的就是使用括号(圆括号)而不是方括号(方括号),然后您将获取生成器而不是列表。现在,每次您在 sList: 中执行
for 行:
时,它都会从前一个停止的位置重新开始(大概是因为break
)——这就是您所做的正在要求,对吗?Just use a generator expression (genexp) instead of the list comprehension (listcomp) you're now using - i.e.:
that's all -- if you're otherwise happy with your code (splitting by os.linesep, even though normal text I/O in Python will already have translated those into
\n
...), all you need to do is to use parentheses (the round kind) instead of brackets (the square kind), and you'll get a generator instead of a list.Now, each time you do a
for line in sList:
, it will start again from where the previous one had stopped (presumably because of abreak
) -- that's what you're asking for, right?使用另一个迭代器:
Use another iterator:
尝试结合使用切片和
enumerate()
:Try using a combination of slices and
enumerate()
:破解迭代器?
然后只需在循环中调用 iterOverList() 几次,它就会保留状态吗?
Hack at an iterator?
Then just call iterOverList() within a loop a few times, it'll retain state?