python函數map

  • 2020 年 1 月 13 日
  • 筆記

map(function, iterable, …)

Apply function to every item of iterable and return a list of the results. 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 withNoneitems. If function isNone, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

Apply function to every item of iterable and return a list of the results.

將可迭代的iterable參數中的每一個元素作為function的參數執行,將結果作為一個列表返回。

>>> def foo(a):  ...    return a**a  ...   >>> a  [1, 2, 3]  >>> map(foo,a)  [1, 4, 27]  >>>

 If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.

如果有多個可迭代的參數,所有的iterables會同時傳遞相同位置的元素給function(並行)

>>> def add(a,b):  ... return a+b  ...   >>> a=[1,2,3]  >>> b=[4,5,6]  >>> map(add,a,b)  [5, 7, 9]  >>>

翻譯不了了:

就這樣吧。

>>> c  [7, 8]  >>> a  [1, 2, 3]  >>> map(add,a,c)  Traceback (most recent call last):    File "<stdin>", line 1, in <module>    File "<stdin>", line 2, in add  TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'  >>> map(mm,a,c)  Traceback (most recent call last):    File "<stdin>", line 1, in <module>  NameError: name 'mm' is not defined  >>> map(None,a,c)  [(1, 7), (2, 8), (3, None)]  >>> a  [1, 2, 3]  >>> b  [4, 5, 6]  >>> map(None,a,b)  [(1, 4), (2, 5), (3, 6)]  >>> c  [7, 8]  >>> map(None,a,c)  [(1, 7), (2, 8), (3, None)]  >>>