python - 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
但这只是给了我第一场比赛。
我怎样才能跳过第一场比赛而只使用第二场比赛?
解决方案
可能不是最好的解决方案,但您可以使用标志来检查您是否已经找到第一次出现
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)
我认为这应该给你第二次出现
推荐阅读
- php - 如何在codeigniter中选择最大数据
- vba - 从多个工作簿复制具有不同列和工作表名称的数据 - VBA
- html - 使用 ASP.NET MVC Helpers 自定义样式的单选按钮
- pyspark - Pyspark:添加新列的行值总和超过 255 列
- arrays - 尝试看看是否有更好的方法来重建对象
- html - 如何使嵌入式 Twitter 提要在尺寸上响应较小的屏幕?
- c - 退出带有特定字母的程序
- amazon-web-services - AWS Lambda SQS 触发器限制/限制
- android - 为 firebase 数据库中的回收站视图设置搜索视图
- laravel - Laravel 5.6 Hosting bootstrap/cache config.php 如何更改文件路径?