How to write this as a list comprehension?
Rustom Mody
rustompmody at gmail.com
Sat Jan 18 10:20:11 EST 2014
On Saturday, January 18, 2014 2:06:29 PM UTC+5:30, Peter Otten wrote:
> Options I can think of:
> You could do it in two steps...
> time_name_pairs = ((localtime(then), name) for then, name in mylist)
> labels = [somefunc(t.tm_mon, t.tm_mday, t.tm_wday, name)
> for t, name in time_name_pairs]
> ...or you could inline the helper function...
> mon_mday_wday = operator.attrgetter("tm_mon", "tm_day", "tm_wday")
> labels = [somefunc(*mon_mday_wday(localtime(then)), name=name)
> for then, name in mylist]
> -- but both seem less readable than the classical for-loop.
> 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!
See it across > 1 line (as I guess it will come after being posted!) and its not so neat.
More information about the Python-list
mailing list