Python检查多个列表的相似性 [英] Python Checking Multiple Lists For Similarities
问题描述
例如,我有3个列表
list1=['Oh','My','god','I','A','List!']
list2=['Oh','What','You','Dramatic?']
Keyword=['I','Dunno','What','You','Talking','About','DOT']
编辑
我想分别比较列表1和2的关键字.它将变成:
I Want to compare keywords with list 1 and 2 separately. so it would become:
编辑
common=['What','I','You']
如果我有10个以上的列表怎么办? <-可选问题.
What if i had more than 10 lists? <-- optional question.
推荐答案
由于您的评论表明您希望项目同时存在于Keyword
和 >或list2
,您可能不希望三者相交.相反,您应该获取list1
和list2
的并集,然后获取该结果与Keyword
的交集.
Since your comment indicates that you want items that exist in both Keyword
and either list1
or list2
, you probably don't want an intersection of all three. Instead you should get the union of list1
and list2
, and then get the intersection of that result and Keyword
.
类似以下内容应该可以为您提供所需的内容:
Something like the following should give you what you want:
common = list((set(list1) | set(list2)) & set(Keyword))
或者是一种更具扩展性的替代方法(感谢Karl的简化版):
Or an alternative approach that is more extensible (thanks to Karl for the shortened version):
lists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10]
common = list(set().union(*lists).intersection(Keyword))
这篇关于Python检查多个列表的相似性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!