How to apply a function to a collection of elements
Consider I have an array of开发者_StackOverflow中文版 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
A generator expression:
(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)
精彩评论