首先,你已經開始使用集,所以你一定要使用他們,因爲他們檢查時,圍堵更快。另外,還有一些已經是設置了幾個有用的內置功能,因此比較兩個列表,你可以相交集,以獲得那些在這兩個列表中的項目:
>>> 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是在任何列表1的子表中的所有項目
>>> set1 | set2
{1, 2, 3, 4, 5, 7, 8, 9}
所以,那麼你可以相交的所有帶有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}
注意,我更換的功能參數的順序,因此主列表(在你的情況列表2)首先提到因爲這是一個別人都相比。
對於後一種情況,您的預期產出是多少?你只想找到* all *列表中的所有數字,或'list1'列表中任何*列表中的'list2'中的數字? – poke