Mapping values of different iterables

suggest change

For example calculating the average of each i-th element of multiple iterables:

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]

There are different requirements if more than one iterable is passed to map depending on the version of python:

def median_of_three(a, b, c):
    return sorted((a, b, c))[1]

list(map(median_of_three, measurement1, measurement2))
TypeError: median_of_three() missing 1 required positional argument: ‘c’
list(map(median_of_three, measurement1, measurement2, measurement3, measurement3))
TypeError: median_of_three() takes 3 positional arguments but 4 were given
import operator

measurement1 = [100, 111, 99, 97]
measurement2 = [102, 117]

# Calculate difference between elements
list(map(operator.sub, measurement1, measurement2))
TypeError: unsupported operand type(s) for -: ‘int’ and ‘NoneType’
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]
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]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents