您可以使用内置函数
map来执行此操作。
因此,如果您要应用的函数是
len,则可以执行以下操作:
>>> list_of_lists = [['how to apply'],['a function'],['to each list?']]>>> map(len, list_of_lists)[1, 1, 1]
在中
Python3,上面返回了一个地图迭代器,因此您需要一个显式
list调用:
>>> map(len, list_of_lists)<map object at 0x7f1faf5da208>>>> list(map(len, list_of_lists))[1, 1, 1]
如果您要为此编写一些必须在Python2和Python3中都兼容的代码,则列表推导方法是可行的。就像是:
[apply_function(item) for item in list_of_lists]
无需任何更改即可在Python 2和3中使用。
但是,如果您输入的list_of_lists很大,则
map在Python3中使用将更有意义,因为迭代器会更快。



