首页 > 解决方案 > Python 3:查找行并跳过第一个匹配项

问题描述

我有一个很长的文件,我必须在其中寻找一个特定的值。问题是这个文件有两行以相同的方式开始,但我需要打印第二行。

该文件类似于:

... random text
Total = 910 K. #Don't need it
... more random lines
Total = 1000 K #The one I need it

我在用着:

for i,line in enumerate(lines):
    if line.find('Total =') != -1:
        Total = line.split()[4]
        break

但这只是给了我第一场比赛。

我怎样才能跳过第一场比赛而只使用第二场比赛?

标签: python

解决方案


可能不是最好的解决方案,但您可以使用标志来检查您是否已经找到第一次出现

is_second_occurance = False
for i,line in enumerate(lines):
    if line.find('Total =') != -1:
        if is_second_occurance:
            total = line.split()[4]
            break
        else:
            is_second_occurance = True

更好的解决方案可能是将其分解为返回生成器的函数

def get_total(lines):
    for line in lines:
        if line.startswith("Total = "):
            yield line.split()[4]

total = get_total(lines)
total = get_total(lines)

我认为这应该给你第二次出现


推荐阅读