replace 'apply' with extended call
__peter__ at web.de
Mon Oct 25 17:15:34 CEST 2004
Alan G Isaac wrote:
> "Andrew Dalke" <adalke at mindspring.com> wrote in message
> news:b61fd.1486$kM.997 at newsread3.news.pas.earthlink.net...
>> How about a solution which replaces the 'map' with a
>> list comprehension?
>> def apply_each(fns, args = ):
>> return [fn(*args) for fn in fns]
>> Conversion to lambda form is trivial for this case but I
>> figured if you're going to name it, why use a lambda?
> This raises another (newbie) question that I had.
> Take a trivial example:
> from operator import truth
> bool1 = lambda lst: map(truth, lst)
> def bool2(lst): return map(truth,lst)
> def bool3(lst): return [truth(_) for _ in lst]
> To my eyes, the most natural is bool2.
> I would never have considered bool1 if
> I had not come across it in the Merz book,
> but it is both shortest and clear.
> I include bool3 just for comparison: I think
> the way in which it is harder to read illustrates
> the usefulness of 'map'.
> So, are there any obvious considerations when
> making a choice among these. In particular,
> why might someone prefer the style in bool1?
I agree with you that using lambda is bad style for defining a named
function. I also prefer map() over list comprehensions if the expression is
a simple call to a predefined function, but a list comprehension is much
more flexible as it allows for expressions instead of function calls and
covers the functionality of filter() and map() in one pass. Personally, I
would just use the inline version of bool2, i. e. write
>>> map(bool, ["", , 0, 0.0])
[False, False, False, False]
directly without bothering to define a function first. I didn't know about
truth(), but it seems to be equivalent to bool() - so why bother with the
More information about the Python-list