Python built-in functions (40) -- map, python built-in Function map
English document:
-
map
(
Function,
Iterable,
...)
-
Return an iterator that applies
FunctionTo every item
Iterable, Yielding the results. If additional
IterableArguments are passed,
FunctionMust take that parameter arguments and is applied to the items from all iterables in parallel. with multiple iterables, the iterator stops when the shortest iterable is exhausted. for cases where the function inputs are already arranged into argument tuples, see
itertools.starmap()
.
-
Note:
-
1. A function accepts one function type parameter, one or more iteratable object parameters, and returns an iterator. Each element in the iterator, all are the results after the function parameter instance calls the iteratable object.
>>> a = map(ord,'abcd')>>> a<map object at 0x03994E50>>>> list(a)[97, 98, 99, 100]
2. When multiple iteratable objects are input, the function parameters must provide enough parameters to ensure that the value of the same index of each iteratable object can be correctly transmitted to the function.
>>> A = map (ord, 'abc') >>> list (a) [97, 98, 99,100] >>> a = map (ord, 'abc ', 'efg') # input two iteratable objects. Therefore, the input function must be able to receive two parameters. ord cannot receive two parameters. Therefore, an error is returned> list () traceback (most recent call last): File "<pyshell #22>", line 1, in <module> list (a) TypeError: ord () takes exactly one argument (2 given) >>> def f (a, B): return a + B >>> a = map (f, 'abcd', 'efg ') # The f function can accept two parameters> list (a) ['AE', 'bf', 'cg ']
3. When multiple iteratable objects are input and their element lengths are inconsistent, the generated iterator only has the shortest length.
>>> Def f (a, B): return a + B >>> a = map (f, 'abcd', 'efg ') # Set the shortest length to 3 >>> list (a) ['AE', 'bf', 'cg ']
4. map functions are a typical functional programming example.