【发布时间】:2023-03-10 08:55:01
【问题描述】:
我有 one.txt 包含数据的文件:
822.25 111.48 883.59 256.68
822.25 111.48 883.59 256.68
8.6 123.68 467.27 276.69
0.0 186.77 165.62 375.0
0.0 186.77 165.62 375.0
724.76 177.83 923.52 316.78
724.76 177.83 923.52 316.78
724.76 177.83 923.52 316.78
724.76 177.83 923.52 316.78
724.76 177.83 923.52 316.78
438.03 148.5 540.88 198.54
511.99 170.97 571.74 215.81
511.99 170.97 571.74 215.81
对于重复的行,我只想为它们写一行。例如:
724.76 177.83 923.52 316.78
重复5次,我只想写一次,对其他行也做同样的事情,然后将新数据写入文件。
我的代码:
with open('one.txt', 'r') as infile:
with open('output.txt', 'w') as outfile:
for line in infile:
#how to do this?
if line are repeated remove and replace them with only one line
outfile.write(line)
【问题讨论】:
-
您的意思是“立即重复”还是“在任何地方重复”?对于前者,这是一个以“last_input”作为循环变量的简单循环。对于后者,可以使用排序图来完成,或者,如果您不关心唯一行的顺序,您可以先对行进行排序,然后使用“立即重复”版本的代码。
-
如果是一次性练习,您可以使用 linux 命令。排序 yourfile.txt | uniq -u
标签: python