在Python中显示没有相邻重复项的文件

时间:2015-12-03 01:03:20

标签: python duplicates

我正在尝试编写一个显示文本文件的文件所以我希望程序在删除任何相邻的相同行时显示该文件。我的问题是代码没有工作,因为我知道我错过了一些东西,我想知道如何为我面临的这个问题编写线条?

input

1 
1 
2 
2 
1 
3 
1 
1 
1


then the output should be:
1 
2 
1 
3 
1

我现在写的代码是:

lines = open('list.txt', 'r').readlines()

lines_set = set(lines)

out  = open('list.txt', 'w')

for line in lines_set:
    out.write(line)

print(set(f.readlines()))

1 个答案:

答案 0 :(得分:2)

正如对问题的评论所述,set()不是您想要的,因为它会删除所有重复项,而不仅仅是相邻的重复项。你需要更像这样的东西:

with open(r'C:\Users\Gord\Desktop\list_in.txt', 'r') as f_in:
    lines = f_in.readlines()

with open(r'C:\Users\Gord\Desktop\list_out.txt', 'w') as f_out:
    prev_line = ''
    for line in lines:
        if line != prev_line:
            f_out.write(line)
            prev_line = line

with open(r'C:\Users\Gord\Desktop\list_out.txt', 'r') as f:
    for line in f.readlines():
        print(line),