gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:18:18 25 4
gpt4 key购买 nike

我正在尝试编写一个显示文本文件的文件,因此我希望程序在删除任何相邻的相同行的同时显示该文件。我的问题是代码不起作用,因为我知道我遗漏了一些东西,并且我想知道如何为我面临的这个问题编写代码行?

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()))

最佳答案

正如问题评论中提到的,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),

关于python - 在 Python 中显示没有相邻重复项的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34056072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com