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

后端 未结 5 1327
南笙
南笙 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:06

    Map is your friend! map takes a function and an iterable (list, for example) and applies the function on each element of the list.

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

    Output

    [1, 1, 1]
    

    If you wanted to do more granular calculation on elements of the sublist, you can nest the map:

    map(lambda x: map(lambda y: y + 1, x), [[1], [1, 2], [1, 2, 3]])
    

    Output

    [[2], [2, 3], [2, 3, 4]]
    

    Another possible approach (also from functional programming) are list comprehensions. List comprehension is a way of constructing a list from iterable in Python. The syntax is [element for element in iterable]. Any computation can be done on the element, so

    [f(element) for element in iterable]
    

    means that the resulting list will be a list of elements, where each element is the result of function f. Like map, list comprehension can be further nested, resulting in a nested element function application.

    [element + 1 for element in el] for el in [[1], [1, 2], [1, 2, 3]]]
    

    Output

    [[2], [2, 3], [2, 3, 4]]
    

提交回复
热议问题