Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

How to apply a function to each sublist of a list in 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...