Consider the following code:
>>> colprint([
(name, versions[name][0].summary or '')
for name in sorted(versions.keys())
])
What this code does is to print the elements of the dictionary versions
in ascending order of its keys
, but since the value
is another sorted list, only the summary of its first element (the 'max') is printed.
Since I am familiar with let
from lisp, I rewrote the above as:
>>> colprint([
(name, package.summary or '')
for name in sorted(versions.keys())
for package in [versions[name][0]]
)]
Do you think this violates being Pythonic? Can it be improved?
Note: For the curious, colprint
is defined here.
Why not exploit tuples?
colprint([(name, version[0].summary or '')
for (name, version) in sorted(versions.iteritems())])
or, even
colprint(sorted([(name, version[0].summary or '')
for (name, version) in versions.iteritems()]))
Also, you may consider (in my first example) removing the []
s, because that way you get a generator instead of a list (which may or may not be useful, since I'm guessing this'll print the whole array, so you won't be saving any evaluations).
I wouldn't use the "tricky for clause" (or "let-equivalent") in most cases, but I would if it's the natural way to avoid repetition, especially costly repetition. E.g.
xs = [(y, y*1.2, y-3.4) for z in zs for y in [somefun(z)] ]
looks much better to me than calling somefun
three times!-) So, it's worth keeping in mind, even if probably not worth using where it does not remove repetition.
So you're using "for x in [y]" as a substitute for "let x y".
Trying to emulate language's syntax in another language is never a good idea. I think that the original version is much clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With