Functional Python Programming

(Wang) #1

The Itertools Module


Applying a function to data via starmap() and map()


The built-in map() function is a higher-order function that applies a map() function
to items from an iterable. We can think of the simple version of the map() function,
as follows:


map(function, arg_iter) == (function(a) for a in arg_iter)


This works well when the arg_iter parameter is a list of individual values. The
starmap() function in the itertools module is simply the *a version of the map()
function, which is as follows:


starmap(function, arg_iter) == (function(*a) for a in arg_iter)


This reflects a small shift in the semantics of the map() function to properly handle
a tuple-of-tuples structure.


The map() function can also accept multiple iterables; the values from these
additional iterables are zipped and it behaves like the starmap() function. Each
zipped item from the source iterables becomes multiple arguments to the given
function.


We can think of the map(function, iter1, iter2, ..., itern) method being
defined as the following two commands:


(function(*args) for args in zip(iter1, iter2, ..., itern))


starmap(function, zip(iter1, iter2, ..., itern))


Various iterator values are used to construct a tuple of arguments via the *args
construct. In effect, starmap() function is like this more general case. We can build
the simple map() function from the more general starmap() function.


When we look at the trip data, from the preceding commands, we can redefine the
construction of a Leg object based on the starmap() function. Prior to creating Leg
objects, we created pairs of points. Each pair looks as follows:


((Point(latitude=37.54901619777347, longitude=-76.33029518659048),
Point(latitude=37.840832, longitude=-76.273834)), ...,
(Point(latitude=38.330166, longitude=-76.458504),
Point(latitude=38.976334, longitude=-76.473503)))


We could use the starmap() function to assemble the Leg objects, as follows:


with urllib.request.urlopen(url) as source:


path_iter = float_lat_lon(row_iter_kml(source))


pair_iter = legs(path_iter)

Free download pdf