如何将函数应用于python中列表的每个子列表? [英] How to apply a function to each sublist of a list in python?
问题描述
假设我有一个这样的列表:
list_of_lists = [['如何申请'],['一个函数'],['到每个列表?']]
我有一个函数,假设我想将 F
函数应用于 F
函数的每个子列表,可以计算关于两个列表的一些分数.如何将这个 F
函数应用到 list_of_lists
的每个列表,并像这样返回一个新列表中的每个分数:
new_list = [score_1, score_2, score_3]
我尝试使用 map
函数执行以下操作:
map(F, list_of_lists).append(new_list)
您可以使用内置的 map
来做到这一点.
所以如果你想应用的函数是len
,你会这样做:
在Python3
中,上面返回一个map迭代器,所以你需要一个显式的list
调用:
<小时>
如果您想为此编写一些必须在 Python2 和 Python3 中都兼容的代码,那么列表推导式是您的最佳选择.类似的东西:
[apply_function(item) for item in list_of_lists]
无需任何更改即可在 Python 2 和 3 中运行.
但是,如果您的输入 list_of_lists 很大,在 Python3 中使用 map
会更有意义,因为迭代器会更快.
Lets say I have a list like this:
list_of_lists = [['how to apply'],['a function'],['to each list?']]
And I have a function let's say I want to apply the F
function to each sublist of the F
function can compute some score about two lists. How can apply this F
function to each list of list_of_lists
and return each score in a new list like this:
new_list = [score_1, score_2, score_3]
I tried with the map
function the following:
map(F, list_of_lists).append(new_list)
You can use the builtin map
to do this.
So if the function you want to apply is len
, you would do:
>>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
>>> map(len, list_of_lists)
[1, 1, 1]
In Python3
, the above returns a map iterator, so you will need an explicit list
call:
>>> map(len, list_of_lists)
<map object at 0x7f1faf5da208>
>>> list(map(len, list_of_lists))
[1, 1, 1]
If you are looking to write some code for this which has to be compatible in both Python2 and Python3, list comprehensions are the way to go. Something like:
[apply_function(item) for item in list_of_lists]
will work in both Python 2 and 3 without any changes.
However, if your input list_of_lists is huge, using map
in Python3 would make more sense because the iterator will be much faster.
这篇关于如何将函数应用于python中列表的每个子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!