通过比较两个列表删除特定单词

2024-03-28 14:41:28 发布

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

我有两张单子。在

x=['billed_qty','billed_amt','sale_value']

y=['george billed_qty', 'sam billed_amt', 'ricky sale_value', 'donald billed_qty']

我需要消除列表y中出现在列表x中的单词,并希望结果列表为:

^{pr2}$

我怎样才能做到这一点?在

谢谢


Tags: 列表valuesamsale单词单子qtygeorge
3条回答

regexlist comprehension一起使用:

comp = re.compile('|'.join(x))
z = [re.sub(comp, '', i).strip() for i in y]

print(z)
['george','sam','ricky','donald']

在列表理解中使用str.joinstr.split

z = [' '.join(w for w in s.split() if w not in x) for s in y]
print(z)

输出:

^{pr2}$

为什么不:

print([' '.join(set(i.split()).difference(set(x))) for i in y])

输出:

^{pr2}$

相关问题 更多 >