用python调试列表

2024-04-27 03:42:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个py脚本(来自Comparing large files with grep or pythonalexander),用于调试两个字符串列表。你知道吗

现在我想修改它以调试列表并删除重复的字符串:

filename_1 = 'A.txt'
filename_2 = 'B.txt'
filename_3 = 'C.txt'
with open(filename_1, 'r') as f1, open(filename_2, 'r') as f2, open(filename_3, 'w') as fout:
    s = set(val.strip() for val in f1.readlines())
    for row in f2:
        row = row.strip()
        if row not in s:
            fout.write(row + '\n')

清单内容:

 A.txt
 string1
 string2

 B.txt
 string1
 string3

预期结果:

 C.txt
 string1
 string2
 string3

谢谢

警察:我是新来的,我道歉。我真正需要的是从列表A中删除B的内容。无论如何,谢谢。你知道吗

这是答案,经过研究(3个案例):

从A.txt列表中删除B.txt内容并退出到C.txt

a=set(line.strip().lower() for line in open('A.txt').readlines())
b=set(line.strip().lower() for line in open('B.txt').readlines())
open("C.txt", "w").write("\n".join(a.difference(b)))

比较A.txt和B.txt,并在C.txt中显示新行B.txt

a=set(line.strip().lower() for line in open('A.txt').readlines())
b=set(line.strip().lower() for line in open('B.txt').readlines())
open("C.txt", "w").write("\n".join(b.difference(a)))

将A.txt和B.txt的内容合并到C.txt中

a=set(line.strip().lower() for line in open('A.txt').readlines())
b=set(line.strip().lower() for line in open('B.txt').readlines())
open("C.txt", "w").write("\n".join(b | a))

Tags: intxt内容列表foraslineopen
1条回答
网友
1楼 · 发布于 2024-04-27 03:42:02

文件的第一部分包含f2中那些不在f1中的项,因此只需将f1的所有内容添加到结果中即可。你知道吗

with open(filename_1, 'r') as f1, open(filename_2, 'r') as f2, open(filename_3, 'w') as fout:
    s = set(val.strip() for val in f1.readlines())
    for row in f2:
        row = row.strip()
        if row not in s:
            fout.write(row + '\n')
    for row in s:
        fout.write(row + '\n')

相关问题 更多 >