Understanding the map function

后端 未结 6 1386
广开言路
广开言路 2020-11-22 06:45
map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed

6条回答
  •  长情又很酷
    2020-11-22 07:14

    Simplifying a bit, you can imagine map() doing something like this:

    def mymap(func, lst):
        result = []
        for e in lst:
            result.append(func(e))
        return result
    

    As you can see, it takes a function and a list, and returns a new list with the result of applying the function to each of the elements in the input list. I said "simplifying a bit" because in reality map() can process more than one iterable:

    If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items.

    For the second part in the question: What role does this play in making a Cartesian product? well, map() could be used for generating the cartesian product of a list like this:

    lst = [1, 2, 3, 4, 5]
    
    from operator import add
    reduce(add, map(lambda i: map(lambda j: (i, j), lst), lst))
    

    ... But to tell the truth, using product() is a much simpler and natural way to solve the problem:

    from itertools import product
    list(product(lst, lst))
    

    Either way, the result is the cartesian product of lst as defined above:

    [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
     (2, 1), (2, 2), (2, 3), (2, 4), (2, 5),
     (3, 1), (3, 2), (3, 3), (3, 4), (3, 5),
     (4, 1), (4, 2), (4, 3), (4, 4), (4, 5),
     (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
    

提交回复
热议问题