4

我有一段代码用这段代码加载了 2 个列表:

with open('blacklists.bls', 'r') as f:
            L = [dnsbls.strip() for dnsbls in f]
with open('ignore.bls', 'r') as f2:
            L2 = [ignbls.stip() for ignbls in f2]

dnsbls 包含:

list1
list2
list3

ignbls 包含

list2

我想要做的是合并 dnsbls 和 ignbls,然后删除任何出现多次的行并用“for”打印这些行。我在想类似的事情:

for combinedlist in L3:
            print combinedlist

在 aboe 示例中将打印出:

list1
list3
4

2 回答 2

2

您需要使用集合而不是列表:

L3 = list(set(L).difference(L2))

示范:

>>> L=['list1','list2','list3']
>>> L2=['list2']
>>> set(L).difference(L2)
set(['list1', 'list3'])
>>> list(set(L).difference(L2))
['list1', 'list3']

出于您的目的,您可能不必再次将其转换回列表,您可以很好地迭代结果集。

于 2012-11-23T13:09:23.913 回答
1

如果忽略小于黑名单(我认为通常是这种情况),那么(未经测试):

with open('blacklists.bls') as bl, open('ignore.bls') as ig:
    bl_for = (line.strip() for line in bl if 'for' not in line)
    ig_for = (line.strip() for line in ig if 'for' not in line)
    res = set(ig_for).difference(bl_for)
于 2012-11-23T13:14:00.473 回答