List comprehensions' ugliness (Was: Re: How to explain exactly what "def" does?)
jerf at compy.attbi.com
jerf at compy.attbi.com
Thu Feb 6 07:26:31 CET 2003
On Wed, 05 Feb 2003 18:24:15 +0100, holger krekel wrote:
> It's nice to use list comprehensions when you would otherwise need to use
> lambda constructs (anonymous functions). consider
List comprehensions also give an additional place to stick a function that
filter does not have, which is easily my #1 use for them:
Suppose something like:
-----
class SomeStruct:
def __init__(...):
self.a = ...
self.b = ...
self.c = ...
l = [some list of SomeStructs]
-----
which is obviously a frequent case. List comprehensions make dealing with
this structure so easy that you can profitably use the Python interpreter
by hand to ask a lot of simple questions.
maxA = max([x.a for x in l])
allBs = [x.b for x in l]
maxAll = [max(x.a, x.b, x.c) for x in l]
oddSums = [x.a+x.b+x.c for x in l if x.a % 2]
stupidSerialization = "\n".join([','.join(x.a, x.b, x.c) for x in l])
In my experience (admittedly highly personal based on applications), the
real juice of LC's is the extreme flexibility of the first component,
which can't even be matched by the theoretically corresponding "map" call,
which requires either a function or a lambda, both of which are
significantly more difficult to write then "x.b" for the second case, for
instance. And I have, for real projects, taken advantage of Python to
collect a lot of data and stick it in nice data structures, then basically
just queried it with LCs and a few small convenience functions, mostly
built out of other LCs. For interactive list processing LCs put Python in
the running with anything else you could name, and for generalized list
processing (rather then number-specific/specialized ones such as Matlab or
Octave gives you) probably just about the best.
More information about the Python-list
mailing list