Python-在排除空集的条件下对多个集进行交集



Python中在排除空集(如果有的话(的条件下对多个集执行交集的最简单方法是什么?我试着使用列表理解,但在下面的例子中,只有当a不为空时,它才有效。

a = {1, 2, 3}
b = {1, 4, 8, 9}
c = {1, 5, 10, 15}
d = {1, 100, 200}
e = set()
MySets = [b, c, d, e]
result = a.intersection(*[s for s in MySets if s])

只要至少有一个非空集,显式调用set.intersection就会工作:

result = set.intersection(*(s for s in [a, b, c, d, e] if s))

如果所有集都可能为空,请在调用set.intersection之前检查筛选结果。赋值表达式使这一点更容易。

result = set.intersection(*non_empty) if (non_empty := list(x for x in [a, b, c, d, e] if s) else set()

最新更新