如何使用生成器表达式创建多个集合的并集?
假设我有一个集合列表,并且我想获得该列表中所有集合的并集。有没有办法使用生成器表达式来做到这一点?换句话说,如何直接在该列表中的所有集合上创建并集作为frozenset
?
Suppose I have a list of sets and I want to get the union over all sets in that list. Is there any way to do this using a generator expression? In other words, how can I create the union over all sets in that list directly as a frozenset
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用
.union()
方法 。这适用于任何可迭代的可迭代。
Just use the
.union()
method.This works for any iterable of iterables.
我认为您想要避免的是在建立联合时中间创建 freezeset 对象?
这是一种方法。 注意:最初使用了
itertools.chain()
但是,正如 Kenny 的评论所指出的,下面的版本稍微好一些:像这样调用:
I assume that what you're trying to avoid is the intermediate creations of frozenset objects as you're building up the union?
Here's one way to do it. NOTE: this originally used
itertools.chain()
but, as Kenny's comment notes, the version below is slightly better:Invoke like this:
嵌套生成器表达式。但我认为它们有点神秘,所以 KennyTM 建议的方式可能更清楚。
Nested generator expression. But I think they are a bit cryptic, so the way KennyTM suggested may be clearer.