[Python-Dev] Re: accumulator display syntax
David Eppstein
eppstein at ics.uci.edu
Sat Oct 25 12:03:01 EDT 2003
In article <200310251618.42221.aleaxit at yahoo.com>,
Alex Martelli <aleaxit at yahoo.com> wrote:
> On Wednesday 22 October 2003 05:27 am, David Eppstein wrote:
> ...
> > Currently, I am using expressions like
> >
> > pos2d =
> > dict([(s,(positions[s][0]+dx*positions[s][2],positions[s][1]+dy*positions[s
> > ][2]))
> > for s in positions])
>
> I _must_ be getting old -- it would never occur to me to write something
> as dense and incomprehensible (and no, removing the "dict([" would not
> make it much clearer). Something like:
>
> pos2d = {}
> for s, (x, y, delta) in positions.iteritems():
> pos2d[s] = x+dx*delta, y+dy*delta
>
> seems just SO much clearer and more transparent to me.
I like the comprehension syntax so much that I push it harder than I
guess I should. If I'm building a dictionary by performing some
transformation on the items of another dictionary, I prefer to write it
in a way that avoids sequencing the items one by one; I don't think of
that sequencing as an inherent part of the loop.
Put another way, I prefer declarative to imperative when possible.
Let's try to spread it out a little and use intermediate variable names:
pos2d = dict([(s, (x + dx*z, y + dy*z))
for s,(x,y,z) in positions.items()])
Better?
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
More information about the Python-Dev
mailing list