映射不同迭代的值

例如,计算多个迭代的每个 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.imapfuture_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]