gpt4 book ai didi

Python - 比较列表中的值(不是 1 :1 match)

转载 作者:行者123 更新时间:2023-11-30 23:10:22 24 4
gpt4 key购买 nike

我有 2 个 txt 文件,其结构如下:

文件1

LINK1;FILENAME1
LINK2;FILENAME2
LINK3;FILENAME3

文件2

FILENAME1
FILENAME2
FILENAME3

我使用此代码来打印两个文件中包含的“唯一”行:

with open('1.txt', 'r') as f1, open('2.txt', 'r') as f2:
a = f1.readlines()
b = f2.readlines()

non_duplicates = [line for line in a if line not in b]
non_duplicates += [line for line in b if line not in a]

for i in range(1, len(non_duplicates)):
print non_duplicates[i]

问题是,通过这种方式,它会打印两个文件的所有行,我想要做的是搜索 FILENAME1 是否在文件 1 的某一行(同时具有链接和文件名的行)中,并删除这一行。

最佳答案

您需要首先加载 2.txt 中的所有行,然后过滤 1.txt 中包含前者的行。使用setfrozenset来组织“黑名单”,使得每个not in平均运行时间为O(1)。另请注意,f1f2 已经是可迭代的:

with open('2.txt', 'r') as f2:
blacklist = frozenset(f2)

with open('1.txt', 'r') as f1:
non_duplicates = [x.strip() for x in f1 if x.split(";")[1] not in blacklist]

关于Python - 比较列表中的值(不是 1 :1 match),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30715247/

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