在 Python for 循环中索引列表
我正在 for 循环内创建一个 for 循环。我正在循环访问列表并查找包含正则表达式模式的特定字符串。一旦找到该行,我需要搜索以查找特定模式的下一行。我需要存储这两行以便能够解析它们的时间。我创建了一个计数器来跟踪外部 for 循环工作时列表的索引号。我可以使用这样的结构来找到我需要的第二行吗?
index = 0
for lineString in summaryList:
match10secExp = re.search('taking 10 sec. exposure', lineString)
if match10secExp:
startPlate = lineString
for line in summaryList[index:index+10]:
matchExposure = re.search('taking \d\d\d sec. exposure', line)
if matchExposure:
endPlate = line
break
index = index + 1
代码运行,但我没有得到我想要的结果。
谢谢。
I'm making a for loop within a for loop. I'm looping through a list and finding a specific string that contains a regular expression pattern. Once I find the line, I need to search to find the next line of a certain pattern. I need to store both lines to be able to parse out the time for them. I've created a counter to keep track of the index number of the list as the outer for loop works. Can I use a construction like this to find the second line I need?
index = 0
for lineString in summaryList:
match10secExp = re.search('taking 10 sec. exposure', lineString)
if match10secExp:
startPlate = lineString
for line in summaryList[index:index+10]:
matchExposure = re.search('taking \d\d\d sec. exposure', line)
if matchExposure:
endPlate = line
break
index = index + 1
The code runs, but I'm not getting the result I'm looking for.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能应该是
should probably be
根据您的具体需求,您可以仅使用列表上的迭代器,或者使用其中两个作为 itertools.tee。即,如果您想要在第一个模式之后的行中仅搜索第二个模式,则单个迭代器即可:
这不会从
aline搜索行code> 到
somestart
的结尾another
,someend
的 only。如果您需要出于这两个目的搜索它们,即为外部循环保留theiter
本身完整,那么tee
可以提供帮助:这是一般规则的例外文档给出的
tee
:因为
theiter
的推进和anotheriter
的推进发生在代码的不相交部分,并且anotheriter
总是在需要时重新构建(因此推进同时的theiter
是不相关的)。Depending on your exact needs, you can just use an iterator on the list, or two of them as mae by itertools.tee. I.e., if you want to search lines following the first pattern only for the second pattern, a single iterator will do:
This will not search lines from
aline
to the endinganother
forsomestart
, only forsomeend
. If you need to search them for both purposes, i.e., leavetheiter
itself intact for the outer loop, that's wheretee
can help:This is an exception to the general rule about
tee
which the docs give:because the advancing of
theiter
and that ofanotheriter
occur in disjoint parts of the code, andanotheriter
is always rebuilt afresh when needed (so the advancement oftheiter
in the meantime is not relevant).