Understanding the map function

后端 未结 6 1387
广开言路
广开言路 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 06:55

    map isn't particularly pythonic. I would recommend using list comprehensions instead:

    map(f, iterable)
    

    is basically equivalent to:

    [f(x) for x in iterable]
    

    map on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:

    [(a, b) for a in iterable_a for b in iterable_b]
    

    The syntax is a little confusing -- that's basically equivalent to:

    result = []
    for a in iterable_a:
        for b in iterable_b:
            result.append((a, b))
    

提交回复
热议问题