How to write this as a list comprehension?

Rhodri James rhodri at wildebst.org.uk
Sun Jan 19 18:41:02 EST 2014


On Sat, 18 Jan 2014 16:00:45 -0000, Jussi Piitulainen  
<jpiitula at ling.helsinki.fi> wrote:

> Rustom Mody writes:
>
>> On Saturday, January 18, 2014 2:06:29 PM UTC+5:30, Peter Otten wrote:
>>
>> > What would a list-comp with `let` or `where` look like? Would it
>> > win the beauty contest against the loop?
>>
>> For me this is neat
>>
>> [somefunc(mn,day,wd,name) for (then, name) in mylist let  
>> (_,mn,dy,_,_,_,wd,_,_) = localtime(then)]
>>
>> Others may not find it so!

Count me firmly in the "others" camp.  It looks ugly, it flows appallingly  
badly as English, and its only going to get worse as you pile in more  
variables and expressions.  -100 from me.

>> See it across > 1 line (as I guess it will come after being posted!)
>> and its not so neat.
>
> I would write that on three lines anyway, properly indented:
>
>   [ somefunc(mn,day,wd,name)
>     for (then, name) in mylist
>     let (_,mn,dy,_,_,_,wd,_,_) = localtime(then) ]
>
> It could be made to use existing keywords:
>
>   [ somefunc(mn,day,wd,name)
>     for (then, name) in mylist
>     with localtime(then) as (_,mn,dy,_,_,_,wd,_,_) ]

Better, in that it's readable.  It's still storing up trouble, though.

Seriously, what's inelegant about this?

def meaningful_name(then, name):
     _,mn,dy,_,_,_,wd,_,_ = localtime(then)
     return somefunc(mn, dy, wd, name)

...

     [meaningful_name(then, name) for (then, name) in mylist]

I assume there's some good reason you didn't want somefunc() to do the  
localtime() itself?

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list