How to create the union of many sets using a generator expression?

早过忘川 提交于 2019-12-24 05:48:15

问题


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?


回答1:


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.




回答2:


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'])



回答3:


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)


来源:https://stackoverflow.com/questions/41190547/iterable-unpacking-cannot-be-used-in-comprehension-python-3-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!