查找python列表之间的交集/差异
问题内容:
我有两个python清单:
a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)]
b = ['the', 'when', 'send', 'we', 'us']
我需要从a中筛选出与b中相似的所有元素。像这种情况,我应该得到:
c = [('why', 4), ('throw', 9), ('you', 1)]
什么是最有效的方法?
问题答案:
列表理解将起作用。
a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)]
b = ['the', 'when', 'send', 'we', 'us']
filtered = [i for i in a if not i[0] in b]
>>>print(filtered)
[('why', 4), ('throw', 9), ('you', 1)]