简体   繁体   中英

Python create immutable object dynamically

I am trying to create an inmmutable object, specifically a frozenset , from a list after applying some function foo() to all of it's elements. That is to say:

my_list = ['a_1', 'a_2', ... , 'a_n']

given the list my_list , what i want to do is execute over all the elements the function foo() and with the result build a frozenset. Something like this:

my_list = frozenset([foo('a_1'), foo('a_2'), ... ,  foo('a_n')])

I don't know if there is any way to do this in a single pass, because if I am not mistaken, for the creation of the frozen set, we iterate on the elements of the list, which if we add the iterative application of the foo() function, gives me two passes, where my intuition tells me that it could be done in one.

Is there any way to do this by taking advantage of the iteration for the set creation?

Sure, if you want a single pass, use a generator, or in this case, map fits perfectly:

frozenset(map(foo, my_list))

Or with a generator, using a generator expression:

frozenset(foo(x) for x in my_list)

Either use map():

my_set = frozenset(map(foo, my_list))

or a generator:

my_set = frozenset(foo(x) for x in my_list)

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