python向后判断第一个有相同序号的行

有个文本文件如下:
1 123 aaa
2 124 bbb
3 125 ccc flag
4 126 ddd
3 127 eee
3 128 fff

我要找到有着flag标志的这一行, 然后继续往下读,找到与flag这一行有着相同序号的那一行,然后记录下这之间的id。按这个例子来说,就是
有flag的一行为3 125 ccc
然后向下读,只找到第一个序号为3的,也就是3 127 eee这一行,然后就记录下ccc跟eee之间的所有id:125 126(包括ccc)
请问该如何做?

阅读 3k
2 个回答
def get_nos(key):
    start_id = None
    nos = []
    with open('a.txt', 'r') as file:
        for line in file.readlines():
            line_list = line.split(' ')
            id = line_list[0]
            no = line_list[1]

            if line.find(key) > 0:
                start_id = id
                nos.append(no)
                continue
            if start_id and id != start_id:
                nos.append(no)
    return nos

print get_nos('flag')
import re

with open('file.txt', 'r') as file:
    flag_num = 0
    list_id = []
    for line in file.readlines():
        if 'flag' in line:
            flag_num = re.search('(\d+)\s+.*', line).group(1)
            list_id.append(re.search('\d+\s+(\d+)\s+.*', line).group(1))
            continue
        if not flag_num:
            continue
        list_id.append(re.search('\d+\s+(\d+)\s+.*', line).group(1))
        target = re.search('{0}\s+.*'.format(flag_num), line)
        if target:
            print list_id[:-1]
            break

输出结果:

['125', '126']
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题