Gnarlodious
Gnarlodious

Reputation: 324

Multiple operations in a List Comprehension

Say I do something like this:

vList=[1236745404]
fList=[ "<td>{}</td>".format ]
[ f(x) for f, x in zip(fList, vList) ]

But now I want to convert the integer into a time string by feeding it into a multiple process stream.

Pseudocode:

fList=[ "<td>{}</td>".format(time.strftime("%a %H&#58;%M %d %b %y", time.localtime())) ]
[ f(x) for f, x in zip(fList, vList) ]

And what I want to see is:

['<td>Tue 22&#58;23 10 Mar 09</td>']

Is the List Comprehension variable input limited to one operation, or can the output be passed downstream?

Upvotes: 2

Views: 1328

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121654

Your two cases are quite different; in the first you have a callable (str.format) in the second you built a complete string.

You'd need to create a callable for the second option too; in this case a lambda would work:

fList=[lambda t: "<td>{}</td>".format(time.strftime("%a %H&#58;%M %d %b %y", time.localtime(t)))]

This is now a list with one callable, a lambda that accepts one argument t, and returns the result of the full expression where t is passed to time.localtime() then formatted using time.strftime then passed to str.format().

Demo:

>>> import time
>>> vList=[1236745404]
>>> fList=[lambda t: "<td>{}</td>".format(time.strftime("%a %H&#58;%M %d %b %y", time.localtime(t)))]
>>> [f(x) for f, x in zip(fList, vList)]
['<td>Wed 05&#58;23 11 Mar 09</td>']

Upvotes: 4

Related Questions