How to apply a function to each sublist of a list in python?

后端 未结 5 1335
南笙
南笙 2020-12-02 00:34

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 sa

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 01:04

    You can use a list comprehension, like this

    [function_to_be_done(item) for item in list_of_lists]
    

    For example,

    >>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
    >>> [len(item) for item in list_of_lists]
    [1, 1, 1]
    

    Note: Though list comprehensions look like a way to apply a function to all the elements, its main purpose is to construct a new list. So, if you don't want to construct a new list, then just iterate with for loop and call the function.


    Apart from that, you can use the map function in Python 2.7, to apply a function to all the elements and construct a list. For example,

    >>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
    >>> map(len, list_of_lists)
    [1, 1, 1]
    

    But, map returns a map iterator object in Python 3.x. So, you need to explicitly convert that to a list, like this

    >>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
    >>> map(len, list_of_lists)
    
    >>> list(map(len, list_of_lists))
    [1, 1, 1]
    

    You might want to read about, what Guido thinks about map in this post.

    Basically, map would more often demand you to create a new function (mostly people create a lambda function). But in many cases, list comprehension avoids that.

提交回复
热议问题