P
Piet van Oostrum
Hi,
I am looking for an elegant way to write the following code as a list
comprehension:
labels = []
for then, name in mylist:
_, mn, dy, _, _, _, wd, _, _ = localtime(then)
labels.append(somefunc(mn, day, wd, name))
So mylist is a list of tuples, the first member of the tuple is a time
(as epoch offset) and I neeed to apply a function on some fields of the
localtime of it.
I could define a auxiliary function like:
def auxfunc(then, name):
_, mn, dy, _, _, _, wd, _, _ = localtime(then)
return somefunc(mn, day, wd, name)
and then use
[auxfunc(then, name) for then, name in mylist]
or even
[auxfunc(*tup) for tup in mylist]
But defining the auxfunc takes away the elegance of a list comprehension. I would like to integrate the unpacking of localtime() and calling somefunc within the list comprehension, but I don't see a simple way to do that.
somefunc(mn, day, wd, name) for _, mn, dy, _, _, _, wd, _, _ in [localtime(then)]
(i.e. using a list comprehension on a one element list to do the variable shuffling)
works but I don't find that very elegant.
labels = [somefunc(mn, day, wd, name)
for then, name in mylist
for _, mn, dy, _, _, _, wd, _, _ in [localtime(then)]]
Python misses a 'where' or 'let'-like construction as in Haskell.
Anybody has a more elegant solution?
I am looking for an elegant way to write the following code as a list
comprehension:
labels = []
for then, name in mylist:
_, mn, dy, _, _, _, wd, _, _ = localtime(then)
labels.append(somefunc(mn, day, wd, name))
So mylist is a list of tuples, the first member of the tuple is a time
(as epoch offset) and I neeed to apply a function on some fields of the
localtime of it.
I could define a auxiliary function like:
def auxfunc(then, name):
_, mn, dy, _, _, _, wd, _, _ = localtime(then)
return somefunc(mn, day, wd, name)
and then use
[auxfunc(then, name) for then, name in mylist]
or even
[auxfunc(*tup) for tup in mylist]
But defining the auxfunc takes away the elegance of a list comprehension. I would like to integrate the unpacking of localtime() and calling somefunc within the list comprehension, but I don't see a simple way to do that.
somefunc(mn, day, wd, name) for _, mn, dy, _, _, _, wd, _, _ in [localtime(then)]
(i.e. using a list comprehension on a one element list to do the variable shuffling)
works but I don't find that very elegant.
labels = [somefunc(mn, day, wd, name)
for then, name in mylist
for _, mn, dy, _, _, _, wd, _, _ in [localtime(then)]]
Python misses a 'where' or 'let'-like construction as in Haskell.
Anybody has a more elegant solution?