在Python for循环中索引列表

2024-10-08 18:25:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个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

代码运行了,但我没有得到我想要的结果。在

谢谢。在


Tags: inre列表forsearchindexifline
2条回答
matchExposure = re.search('taking \d\d\d sec. exposure', lineString)

应该是的

^{pr2}$

根据您的具体需要,您可以在列表上使用一个迭代器,或者使用其中两个迭代器作为mae by itertools.tee。一、 例如,如果您只想在第一个模式之后的行中搜索第二个模式,那么一个迭代器就可以:

theiter = iter(thelist)

for aline in theiter:
  if re.search(somestart, aline):
    for another in theiter:
      if re.search(someend, another):
        yield aline, another  # or print, whatever
        break

这将而不是搜索从aline到结束somestart的行,只搜索someend的行。如果您需要为这两个目的搜索它们,即让theiter本身保持原样,那么tee可以帮助您:

^{pr2}$

这是关于tee的一般规则的一个例外,文档给出了:

Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.

因为theiter和{}的推进发生在代码不相交的部分,并且{}总是在需要时重新重建(因此{}的推进与此无关)。在

相关问题 更多 >

    热门问题