简体   繁体   English

Python - 在排除空集的情况下,多个集的交集

[英]Python - Intersection on multiple sets on the condition that empty sets are to be excluded

What's the simplest way in Python of performing an intersection on multiple sets on the condition that empty sets, if any, are to be excluded?在排除空集(如果有)的情况下,在多个集上执行交集的 Python 中最简单的方法是什么? I tried using a list comprehension but in the example below, it only works if a is not empty.我尝试使用列表推导式,但在下面的示例中,它仅在 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])

Calling set.intersection explicitly will work as long as there is at least one non-empty set:只要有至少一个非set.intersection显式调用set.intersection就会起作用:

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

If there is a possibility of all sets being empty, check the result of filtering before calling set.intersection .如果有可能所有集合都为空,请在调用set.intersection之前检查过滤结果。 The assignment expression makes this a bit easier.赋值表达式使这更容易一些。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM