python如何把程序写在子函数下,如何将函数应用于Python中的列表中的每个子列表?...

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)

>>> 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值