计算两个列表的所有幂集交集

时间:2018-12-10 18:08:04

标签: python list set intersection

我找到了很多有关查找2个列表的交集的文章,但是没有一篇文章写我如何获得所有的交集(也许可以称为子交集)。

示例:

list1 = ['a', 'b', 'c', 'd']
list2 = ['b', 'c', 'd', 'e']

print (find_all_intersections(list1, list2))

输出:

['b', 'c', 'd', 'bc', 'bd', 'cd', 'bcd']

有什么功能可以做到这一点?

1 个答案:

答案 0 :(得分:4)

嗯,实际上很简单。找到交集后,计算功率集:

from itertools import chain, combinations

s = set(list1).intersection(list2)
[''.join(c) for c in chain.from_iterable(
    combinations(s, r) for r in range(len(s)+1)) if c]

['b', 'c', 'd', 'bc', 'bd', 'cd', 'bcd']

有关生成电源集的更多信息,请参见here

相关问题