首页 > 解决方案 > 检查行是否与文件中的另一行相同

问题描述

我想签入一个文件,它将检查所有行,如果一行与任何其他行相同;代码会说“行号 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!

标签: python

解决方案


像这样,它应该工作:

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}!")

推荐阅读