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

Compute all powerset intersections of two lists

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

示例:

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

print (find_all_intersections(list1, list2))

输出:

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

有什么函数可以做到这一点吗?

其实很简单。找到交点后,计算幂集:

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