首页 > 解决方案 > 如何使用python查找连续行

问题描述

我有一个文件,像这样:

the 1 file is:
none
the 2 file is:
a-h-f
the 3 file is:
a-h-p
the 4 file is:
none

我想用python知道哪些连续的两个文件是竞争的,不是没有。以这个文件为例,“第2个文件”和“第3个文件”是连续的,有内容。我期望的结果是:

   the 2 file is:
   a-h-f
   the 3 file is:
   a-h-p

请有人给我一些提示。谢谢。

标签: python

解决方案


将您的行放在列表中,即文件对象在lines = f.readlines()哪里,或者:f

lines = '''the 1 file is:
none
the 2 file is:
a-h-f
the 3 file is:
a-h-p
the 4 file is:
none
'''.splitlines()

然后:

for t in zip(*[lines[i::2] for i in range(4)]):
    if 'none' not in t:
        # t is ('the 2 file is:', 'a-h-f', 'the 3 file is:', 'a-h-p')
        # do something with it, e.g.:
        for x in t:
            print(x)

印刷:

the 2 file is:
a-h-f
the 3 file is:
a-h-p

推荐阅读