在Python for循环中索引列表

1 投票
2 回答
536 浏览
提问于 2025-04-16 00:21

我正在写一个嵌套的循环,也就是在一个循环里面再放一个循环。我有一个列表,我要在里面找一个包含特定模式的字符串。找到这一行后,我还需要继续查找下一行是否符合某种模式。我需要把这两行都存起来,以便提取出它们的时间。我创建了一个计数器,用来记录外层循环在列表中的索引位置。请问我可以用这样的方式来找到我需要的第二行吗?

 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

代码是可以运行的,但我没有得到我想要的结果。

谢谢。

2 个回答

1
matchExposure = re.search('taking \d\d\d sec. exposure', lineString)
matchExposure = re.search('taking \d\d\d sec. exposure', line)

可能应该是

1

根据你的具体需求,你可以直接在列表上使用一个迭代器,或者使用两个迭代器,这个可以通过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到结束的another之间搜索somestart会搜索someend。如果你需要同时搜索这两种情况,也就是说,要保持theiter本身在外层循环中不变,这时候tee就能派上用场:

for aline in theiter:
  if re.search(somestart, aline):
    _, anotheriter = itertools.tee(iter(thelist))
    for another in anotheriter:
      if re.search(someend, another):
        yield aline, another  # or print, whatever
        break

这条规则是关于tee的一个例外,文档中提到:

一旦tee()进行了分裂,原始的可迭代对象就不应该在其他地方使用;否则,这个可迭代对象可能会在没有通知tee对象的情况下被推进。

这是因为theiteranotheriter的推进发生在代码的不同部分,而anotheriter在需要时总是会重新构建(所以在此期间theiter的推进并不重要)。

撰写回答