python - 检查行是否与文件中的另一行相同
问题描述
我想签入一个文件,它将检查所有行,如果一行与任何其他行相同;代码会说“行号 B 与行号 A 相同”。
------- lines.txt ----------
1 | first line
2 | this line
3 | i am another line
4 | this line
-------------------------
> Alert: Line 4 is same with line 2!
- 如果可能但不重要,请使其更快。
- 如果可能的话,我们能否像只检查第 5、10、15、20 行一样检查每 5 行...
- 实际文件中不存在行号。它们仅用于显示行号。
解决方案
像这样,它应该工作:
with open('lines.txt','r') as f:
lines = f.read().splitlines()
for i1,l1 in enumerate(lines):
for i2,l2 in enumerate(lines[i1+1:]):
if l1 == l2:
print(f"Alert: Line {i1+1} is the same with line {i1+i2+2}!")
推荐阅读
- python - 在A Point Class Python中计算两点之间的距离
- javascript - Dragula 制作可拖动元素外部的拖动手柄
- vue.js - Storybook 中的 Vue:“SassError:未定义的变量”
- python - 根据 shapefile 掩码获取光栅图像的值
- input - ngx-otp-input 中的自动对焦在 ionic 5 中不起作用
- java - ElasticSearch QueryDSL 到 Java 的转换
- java - inApp 更新,下载但未安装
- spring-boot - Spring Data JPA JOIN查询太慢(一一匹配每个条目)
- python - 可以在 Python 中并行化同一数据集上的多个 100k 套索回归吗?
- grpc-java - @WithSpan 不生成日志