How to write this as a list comprehension?

Piet van Oostrum piet at vanoostrum.org
Sun Jan 19 17:06:05 EST 2014


John Allsup <pydev at allsup.co> writes:

> Hi,
>
> I'd agree with the advice that it's not the best idea: readability sucks
> here, but consider the following:
>
>
> import time
>
> def somefunc(a,b,c,d): # dummy function
>     return "{} - {} - {} : {}".format(a,b,c,d)
> l = [(time.time(),"name {}".format(n)) for n in range(100)] # dummy data
>
> # the line in question
> labels = [somefunc(*(lambda t,n:
> (t.tm_mon,t.tm_mday,t.tm_wday,n))(time.localtime(x[0]),x[1])) for x in
> l]
>
>
> print(labels) # just to see the result
>
>
> If you find that hard to decipher, the consider the maintainability of
> code you write that uses such comprehensions.  You need to include
> comments that explain what this does, and it is easier to write a
> longhand version using .append() and variable assignments.  I presume
> performance won't be an issue determining the right approach, since then
> you'd be using C or C++.

I'll stay with

labels = [somefunc(mn, day, wd, name) 
            for then, name in mylist
            for _, mn, dy, _, _, _, wd, _, _ in [localtime(then)]]

where (sic!) the last part means as much as 
           where _, mn, dy, _, _, _, wd, _, _ = localtime(then)

I find the list comprehension preferable because it makes it more clear
that a new list is constructed from an existing list, something that is
not as immediately clear with the append construction.
-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list