python - 如何使用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
请有人给我一些提示。谢谢。
解决方案
将您的行放在列表中,即文件对象在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
推荐阅读
- typescript - 如何让 Typescript 检查返回类型是否与结构完全匹配?
- python - 编写一个函数,将文件名和单个字母作为输入,如果玩家的姓氏以该字符开头,则返回 True
- javascript - 在 Highcahrts 中删除蜘蛛网图表周围的圆圈
- c++ - C++ 通过引用和临时变量传递
- android - Gradle 同步失败:无法找到请求目标的有效证书路径
- java - 如何修复“在当前项目和插件组中找不到前缀'liquibase'的插件”
- parse-platform - 在 Parse-SDK-JS 中设置 StorageController
- c# - 在 ASP.NET Core 3 中从单独的类中使用 Hub
- r - 运行模拟:for 循环中的随机抽样
- r - 如何更改 R 中等高线图颜色栏中刻度标签的字体大小?