我有一段代码用这段代码加载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
答案 0 :(得分:2)
您需要使用sets而不是列表:
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']
出于您的目的,您可能不必再将其转换回列表,您可以对结果集进行迭代。
答案 1 :(得分: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)