まず第一に、あなたはすでにセットを使い始めているので、封じ込めをチェックするときより速いので、あなたは間違いなくそれらを使うべきです。また、セットにはすでにいくつかの便利な組み込み機能があるため、2つのリストを比較するために、セットを交差させるだけで、両方のリストにあるアイテムを取得できます。
>>> set1 = set([1, 2, 3, 4, 5])
>>> set2 = set([3, 8, 9, 1, 7])
>>> set1 & set2
{1, 3}
>>> list(set1 & set2) # in case you need a list as the output
[1, 3]
同様に、2つのセットの和集合を見つけて、いずれかのセットに含まれるアイテムを取得することもできます。
>>> set1 | set2
{1, 2, 3, 4, 5, 7, 8, 9}
したがって、list1のサブリストのいずれかにあるlist2のすべてのアイテムを検索する場合は、すべてのサブリストをlist2と交差させてから、それらすべての結果を結合することができます。
>>> sublists = [set([1, 2, 3, 4, 5]), set([5, 8, 2, 9, 12]), set([3, 7, 19, 4, 16])]
>>> otherset = set([3, 7, 2, 16, 19])
>>> intersections = [sublist & otherset for sublist in sublists]
>>> intersections
[{2, 3}, {2}, {16, 3, 19, 7}]
>>> union = set()
>>> for intersection in intersections:
union = union | intersection
>>> union
{16, 19, 2, 3, 7}
次を使用して、もう少しうまく行うこともできますfunctools.reduce
。
>>> import functools
>>> functools.reduce(set.union, intersections)
{16, 19, 2, 3, 7}
同様に、これらの結果を実際に交差させたい場合は、次のようにすることもできます。
>>> functools.reduce(set.intersection, intersections)
set()
そして最後に、それらすべてを素晴らしい関数に詰め込むことができます。
def compareLists (mainList, *otherLists):
mainSet = set(mainList)
otherSets = [set(otherList) for otherList in otherLists]
intersections = [mainSet & otherSet for otherSet in otherSets]
return functools.reduce(set.union, intersections) # or replace with set.intersection
そして、次のように使用します。
>>> compareLists([1, 2, 3, 4, 5], [3, 8, 9, 1, 7])
{1, 3}
>>> compareLists([3, 7, 2, 16, 19], [1, 2, 3, 4, 5], [5, 8, 2, 9, 12], [3, 7, 19, 4, 16])
{16, 19, 2, 3, 7}
Note, that I replaced the order of the arguments in the function, so the main list (in your case list2) is mentioned first as that is the one the others are compared to.