2010-06-23 81 views
1

我在for循环中做了for循环。我遍历一个列表并找到一个包含正则表达式模式的特定字符串。一旦找到该行,我需要搜索以查找某个特定模式的下一行。我需要存储两行以便能够解析出它们的时间。我创建了一个计数器来跟踪列表的索引号作为外循环工作。我可以使用这样的结构来找到我需要的第二条线吗?在Python 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 

该代码运行,但我没有得到我期待的结果。

谢谢。

+0

您可能还想包含外循环的代码。 – Amber 2010-06-23 20:57:32

+0

而不是手动计数,你可以这样做:'对于索引,在枚举(summaryList)中的行:' – Amber 2010-06-23 22:02:53

回答

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

大概应该是

matchExposure = re.search('taking \d\d\d sec. exposure', line) 
+0

我认为你是对的,但我解决了这个问题,它仍然不会产生正确的输出。我在最里面的if语句中放置了一行打印行,并且没有打印任何内容。 – Hannah 2010-06-23 21:03:38

+0

您正在寻找的第二行始终是曝光时间的3位数字? (另外,您可以使用'\ d {3}'而不是'\ d \ d \ d'。) – Amber 2010-06-23 22:04:13

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搜索线到结束anothersomestart只有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()作出了分拆后,原 可迭代不应该被用来 其他地方;否则,迭代器 可能会得到提前,而不通知对象。

因为theiter推进和的anotheriter发生在代码的分离部分,并anotheriter需要的时候总是重新改建(所以theiter在此期间的发展是不相关)。