如何使用生成器表达式创建多个集合的并集?

发布于 2024-09-13 10:05:41 字数 114 浏览 4 评论 0原文

假设我有一个集合列表,并且我想获得该列表中所有集合的并集。有没有办法使用生成器表达式来做到这一点?换句话说,如何直接在该列表中的所有集合上创建并集作为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

森林散布 2024-09-20 10:05:41

只需使用 .union() 方法

>>> l = [set([1,2,3]), set([4,5,6]), set([1,4,9])]
>>> frozenset().union(*l)
frozenset([1, 2, 3, 4, 5, 6, 9])

这适用于任何可迭代的可迭代。

Just use the .union() method.

>>> l = [set([1,2,3]), set([4,5,6]), set([1,4,9])]
>>> frozenset().union(*l)
frozenset([1, 2, 3, 4, 5, 6, 9])

This works for any iterable of iterables.

烟沫凡尘 2024-09-20 10:05:41

我认为您想要避免的是在建立联合时中间创建 freezeset 对象?

这是一种方法。 注意:最初使用了 itertools.chain() 但是,正如 Kenny 的评论所指出的,下面的版本稍微好一些:

import itertools

def mkunion(*args):
    return frozenset(itertools.chain.from_iterable(args))

像这样调用:

a = set(['a','b','c'])
b = set(['a','e','f'])
c = mkunion(a,b)       # => frozenset(['a', 'c', 'b', 'e', 'f'])

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:

import itertools

def mkunion(*args):
    return frozenset(itertools.chain.from_iterable(args))

Invoke like this:

a = set(['a','b','c'])
b = set(['a','e','f'])
c = mkunion(a,b)       # => frozenset(['a', 'c', 'b', 'e', 'f'])
拒绝两难 2024-09-20 10:05:41

嵌套生成器表达式。但我认为它们有点神秘,所以 KennyTM 建议的方式可能更清楚。

frozenset(some_item for some_set in some_sets for some_item in some_set)

Nested generator expression. But I think they are a bit cryptic, so the way KennyTM suggested may be clearer.

frozenset(some_item for some_set in some_sets for some_item in some_set)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文