對映不同迭代的值
例如,計算多個迭代的每個 i
th 元素的平均值:
def average(*args):
return float(sum(args)) / len(args) # cast to float - only mandatory for python 2.x
measurement1 = [100, 111, 99, 97]
measurement2 = [102, 117, 91, 102]
measurement3 = [104, 102, 95, 101]
list(map(average, measurement1, measurement2, measurement3))
# Out: [102.0, 110.0, 95.0, 100.0]
如果根據 python 的版本將多個 iterable 傳遞給 map
,則有不同的要求:
-
該函式必須採用與迭代一樣多的引數:
def median_of_three(a, b, c): return sorted((a, b, c))[1] list(map(median_of_three, measurement1, measurement2))
TypeError:
median_of_three()
缺少 1 個必需的位置引數:‘c’list(map(median_of_three, measurement1, measurement2, measurement3, measurement3))
TypeError:
median_of_three()
需要 3 個位置引數,但是給出了 4 個
Python 2.x >= 2.0.1
-
map
:只要一個 iterable 仍沒有被完全消耗,迭代就會迭代,但是從完全消耗的 iterables 中假設None
:import operator measurement1 = [100, 111, 99, 97] measurement2 = [102, 117] # Calculate difference between elements list(map(operator.sub, measurement1, measurement2))
TypeError:不支援的運算元型別 - :‘int’和’NoneType’
-
itertools.imap
和future_builtins.map
:只要一個 iterable 停止,對映就會停止:import operator from itertools import imap measurement1 = [100, 111, 99, 97] measurement2 = [102, 117] # Calculate difference between elements list(imap(operator.sub, measurement1, measurement2)) # Out: [-2, -6] list(imap(operator.sub, measurement2, measurement1)) # Out: [2, 6]
Python 3.x >= 3.0.0
-
一旦迭代停止,對映就會停止:
import operator measurement1 = [100, 111, 99, 97] measurement2 = [102, 117] # Calculate difference between elements list(map(operator.sub, measurement1, measurement2)) # Out: [-2, -6] list(map(operator.sub, measurement2, measurement1)) # Out: [2, 6]