2013-08-06 55 views
2

兩個列表我有兩個列表:Python的 - 比較的套

list1 = [ 
    set(['3105']), 
    set(['3106', '3107']), 
    set(['3115']), 
    set(['3122']), 
    set(['3123', '3126', '286']) 
] 

list2 = [ 
    set(['400']), 
    set(['3115']), 
    set(['3100']), 
    set(['3107']), 
    set(['3123', '3126']) 
] 

如何比較這些列表的交集,因此,舉例來說,如果3126是某處任何這兩個列表的集合,它將追加另一個列表與3126.我的最終目標是追加一個單獨的列表,然後採取列表的長度,所以我知道列表之間有多少匹配。

回答

0

您可以拼合的套兩個列表成爲集:

l1 = set(s for x in list1 for s in x) 
l2 = set(s for x in list2 for s in x) 

然後你就可以計算交會:

common = l1.intersection(l2) # common will give common elements 
print len(common) # this will give you the number of elements in common. 

結果:

>>> print common 
set(['3123', '3115', '3107', '3126']) 
>>> len(common) 
4 
+0

'設置(itertools.chain.from_iterable(list1的))'會比嵌套LC更快。 –

+0

感謝您的信息! – jh314

+1

這工作,謝謝! –

2

你不得不合並所有集合;採取在兩個列表集合的聯合,再取這兩個工會的交集:

sets_intersection = reduce(set.union, list1) & reduce(set.union, list2) 

if 3126 in sets_intersection: 
    # .... 
1
>>> common_items = set().union(*list1) & set().union(*list2) 
>>> common_items 
set(['3123', '3115', '3107', '3126']) 
>>> '3126' in common_items 
True 

時序比較:

>>> %timeit reduce(set.union, list1) & reduce(set.union, list2) 
100000 loops, best of 3: 11.7 us per loop 
>>> %timeit set().union(*list1) & set().union(*list2)  #winner 
100000 loops, best of 3: 4.63 us per loop 
>>> %timeit set(s for x in list1 for s in x) & set(s for x in list2 for s in x) 
10000 loops, best of 3: 11.6 us per loop 
>>> %timeit import itertools;set(itertools.chain.from_iterable(list1)) & set(itertools.chain.from_iterable(list2)) 
100000 loops, best of 3: 9.91 us per loop