tags:

views:

79

answers:

3

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
+5  A: 

A generator expression:

(foobar(x) for x in S)
Ignacio Vazquez-Abrams
+1 for idiomatic way to indicate lazily-evaluated transformation of a sequence in Python.
Derrick Turk
+1  A: 

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)
Alexander Gessler
Note that the question is asking for lazy evaluation; a genexp is more appropriate. Not downvoting because this is a valid (but eager-evaluated) alternative. That said, even for eager evaluation a list comprehension would probably be more idiomatic.
Derrick Turk
You're right, I missed the original intent. I'm leaving it here for completeness.
Alexander Gessler
+3  A: 

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.

Robert Rossney
Don't feel bad for the guilty pleasure of using the functional side of Python!
ΤΖΩΤΖΙΟΥ