Python - 比较两个集合列表

时间:2013-08-06 17:07:15

标签: python list intersection set

我有两个清单:

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.我的最终目标是附加一个单独的列表然后取列表的长度,以便知道列表之间有多少匹配。

3 个答案:

答案 0 :(得分:2)

你必须合并所有套装;取两个列表中的集合的联合,然后取这两个联合的交集:

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

if 3126 in sets_intersection:
    # ....

答案 1 :(得分: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

答案 2 :(得分: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