如何将函数应用于Python中的列表中的每个子列表? [英] How to apply a function to each sublist of a list in python?

查看:423
本文介绍了如何将函数应用于Python中的列表中的每个子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  list_of_lists = [['如何申请'],['a函数'],['到每个列表?']] 

我有一个函数让我们说我希望将 F 函数应用于 F 函数的每个子列表可以计算出一些关于两个列表的分数。如何将这个 F 函数应用于 list_of_lists 的每个列表并将每个分数返回到新列表中,如下所示: p>

  new_list = [score_1,score_2,score_3] 

我使用 map 函数尝试以下内容:

  map(F,list_of_lists).append(new_list)


解决方案

你可以使用内建的 map 来执行此操作。



所以如果你想要应用的函数是 len ,你可以这样做:

 >>> list_of_lists = [['如何申请'],['函数'],['给每个列表?]] 
>>> map(len,list_of_lists)
[1,1,1]

Python3 ,上面返回一个映射迭代器,所以你需要一个明确的 list 调用:

 >>> map(len,list_of_lists)
<地图对象在0x7f1faf5da208>
>>> list(map(len,list_of_lists))
[1,1,1]






如果你想为Python2和Python3编写一些兼容的代码,列表解析是一条可行的路。例如:

  [list_of_lists中item的apply_function(item)] 

可以在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆