functional programming with map()
Bengt Richter
bokr at oz.net
Mon Feb 25 00:50:56 EST 2002
On 24 Feb 2002 20:18:53 -0800, Paul Rubin <phr-n2002a at nightsong.com> wrote:
>David Eppstein <eppstein at ics.uci.edu> writes:
>> > : But what is the functional equvalent of:
>> >
>> > : for x in items:
>> > : x.f()
>> >
>> >
>> >
>> > Here's one way to do it:
>> >
>> > ###
>> > map(lambda x: x.f(), items)
>> > ###
>>
>> I'd prefer
>> [x.f() for x in items]
>>
>> It's not functional syntax, but so what?
>
>Both of those build up a new list of the results, instead of
>discarding the values. If the f function takes an integer and
>computes a 20-megabyte structure, you've got a problem. This really
>calls for a generator comprehension as discussed a few weeks back.
>
> reduce(lambda x,y:(y.f(),0)[1], items, 0)
>
>almost works, but invokes f an extra time at the end.
>
>Someone see how to fix it?
>>> class F:
... def __init__(self,msg):
... self.msg = msg
... def f(self):
... print self.msg
...
>>> a=F('this is a')
>>> b=F('this is b')
>>> c=F('this is c')
>>> items = [a,b,c]
>>> reduce(lambda x,y:y.f() and 0, items, 0)
this is a
this is b
this is c
but I didn't get an extra call trying your version:
>>> reduce(lambda x,y:(y.f(),0)[1], items, 0)
this is a
this is b
this is c
0
you can use the 'and 0' ploy to get a zero length
list comprehension also:
>>> [ 0 for x in items if x.f() and 0]
this is a
this is b
this is c
[]
Regards,
Bengt Richter
More information about the Python-list
mailing list