简体   繁体   English

列表推导中的多个操作

[英]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? 列表理解变量输入是否仅限于一种操作,还是可以将输出传递给下游?

Your two cases are quite different; 您的两种情况大不相同; in the first you have a callable ( str.format ) in the second you built a complete string. 在第一个中,您有一个可调用的( str.format );在第二个中,您构建了一个完整的字符串。

You'd need to create a callable for the second option too; 您还需要为第二个选项创建一个可调用对象。 in this case a lambda would work: 在这种情况下,lambda将起作用:

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() . 现在这是一个带有一个可调用的lambda的列表,该lambda接受一个参数t ,并返回完整表达式的结果,其中t传递给time.localtime()然后使用time.strftime进行格式化,然后传递给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>']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM