简体   繁体   中英

How to get listcomprehension result as unpacked list

I have a function (in the example: some_function() ) that returns a set. I got a data structure of some elements (in the example arr ) and need to map the elements to the function and I want to get back a set of all elements. Not a set of sets but a set of all the elements that are in the sets. I know that some_function() only returns one dimensional sets.

I tried to use map but didn't quite get it to work, I got it to work with list comprehensions but I don't really like my solution.

Is it possible to not create a list and then unpack it?
Or can I somehow convert what I get from my map approach without much work?

Example:

arr = [1, 2, 3]

# I want something like this
set.union(some_function(1), some_function(2), some_function(3))

# where some_function returns a set    

# this is my current solution
set.union(*[some_function(el) for el in arr]))

# approach with map, but I couldn't convert it back to a set
map(some_function, arr)

I think your current solution is fine. If you want to avoid creating a list, you may try:

set.union(*(some_function(el) for el in arr)))

You can use a generator expression instead of a list comprehension so that you don't have to create a temporary list first:

set.union(*(some_function(el) for el in arr)))

or, using map :

set.union(*map(some_function, arr))

In Python, sometimes you just have to not be fancy.

result = set()

for el in arr:
    result.update(some_function(el))

This approach doesn't create a list of the return values and so doesn't hold onto sets longer than necessary. You can wrap it in a function for cleanliness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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