python中用来计算集合交集的是_python – 计算集合列表中所有组合的交集

IIUC,这样的事情应该有效:

from itertools import combinations

def venn_count(named_sets):

names = set(named_sets)

for i in range(1, len(named_sets)+1):

for to_intersect in combinations(sorted(named_sets), i):

others = names.difference(to_intersect)

intersected = set.intersection(*(named_sets[k] for k in to_intersect))

unioned = set.union(*(named_sets[k] for k in others)) if others else set()

yield to_intersect, others, len(intersected - unioned)

ns = {"a": {1,2,5,10,12}, "b": {1,2,6,9,12,15}, "c": {1,2,7,8,15}}

for intersected, unioned, count in venn_count(ns):

print 'len({}{}) = {}'.format(' & '.join(sorted(intersected)),

' - ' + ' - '.join(sorted(unioned)) if unioned else '',

count)

这使

len(a - b - c) = 2

len(b - a - c) = 2

len(c - a - b) = 2

len(a & b - c) = 1

len(a & c - b) = 0

len(b & c - a) = 1

len(a & b & c) = 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值