英文文檔: 2. 當傳入多個可迭代對象時,函數的參數必須提供足夠多的參數,保證每個可迭代對象同一索引的值均能正確傳入函數。 3. 當傳入多個可迭代對象時,且它們元素長度不一致時,生成的迭代器只到最短長度。 4. map函數是一個典型的函數式編程例子。 ...
英文文檔:
map
(function, iterable, ...)- Return an iterator that applies function to every item of iterable, yielding 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. 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()
. - 說明:
- 1. 函數接受一個函數類型參數、一個或者多個可迭代對象參數,返回一個可迭代器,此迭代器中每個元素,均是函數參數實例調用可迭代對象後的結果。
>>> a = map(ord,'abcd') >>> a <map object at 0x03994E50> >>> list(a) [97, 98, 99, 100]
2. 當傳入多個可迭代對象時,函數的參數必須提供足夠多的參數,保證每個可迭代對象同一索引的值均能正確傳入函數。
>>> a = map(ord,'abcd') >>> list(a) [97, 98, 99, 100] >>> a = map(ord,'abcd','efg') # 傳入兩個可迭代對象,所以傳入的函數必須能接收2個參數,ord不能接收2個參數,所以報錯 >>> list(a) 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') # f函數可以接受2個參數 >>> list(a) ['ae', 'bf', 'cg']
3. 當傳入多個可迭代對象時,且它們元素長度不一致時,生成的迭代器只到最短長度。
>>> def f(a,b): return a + b >>> a = map(f,'abcd','efg') # 選取最短長度為3 >>> list(a) ['ae', 'bf', 'cg']
4. map函數是一個典型的函數式編程例子。