简体   繁体   中英

How to apply a function to a collection of elements

Consider I have an array of elements out of which I want to create a new 'iterable' which on every next applies a custom 'transformation'. What's the proper way of doing it under python 2.x?

For people familiar with Java, the equivalent is Iterables#transform from google's collections framework.

Ok as for a dummy example (coming from Java)

Iterable<Foo> foos = Iterables.transform(strings, new Function<String, Foo>()
    {
        public Foo apply(String string) {
        return new Foo(string);
        }
    });


//use foos below

生成器表达式:

(foobar(x) for x in S)

Another way of doing it:

from itertools import imap
my_generator = imap(my_function, my_iterable)

That's the way I'd do it myself, but I'm kind of weird in that I actually like map .

Or by using map() :

def foo(x):
   return x**x   

for y in map(foo,S):
   bar(y)

# for simple functions, lambda's are applicable as well
for y in map(lambda x: x**x,S):
   bar(y)

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