Functional Python Programming

(Wang) #1

Working with Collections


The evaluation of the tuple() method actually leads to a proper object being built so
that we can print the output. The flt variable's objects are created only as needed.


There are other refactoring's we might like to do. In general, the source of the data is
something we often want to change. In our example, the lat_lon_kml() function is
tightly bound in the rest of the expression. This makes reuse difficult when we have
a different data source.


In the case where the float() operation is something we'd like to parameterize
so that we can reuse it, we can define a function around the generator expression.
We'll extract some of the processing into a separate function merely to group the
operations. In our case, the string-pair to float-pair is unique to a particular source
data. We can rewrite a complex float-from-string expression into a simpler function
such as follows:


def float_from_pair( lat_lon_iter ):
return ((float(lat), float(lon)) for lat,lon in lat_lon_iter)


The float_from_pair() function applies the float() function to the first and
second values of each item in the iterable, yielding a two tuple of floats created from
an input value. We've relied on Python's for statement to decompose the two tuple.


We can use this function in the following context:


legs( float_from_pair(lat_lon_kml()))


We're going to create legs that are built from float values that come from a KML
file. It's fairly easy to visualize the processing, as each stage in the process is a simple
prefix function.


When parsing, we often have sequences of string values. For numeric applications,
we'll need to convert strings to float, int, or Decimal values. This often involves
inserting a function such as the float_from_pair() function into a sequence of
expressions that clean up the source data.


Our previous output was all strings; it looked like the following code snippet:


(('37.54901619777347', '-76.33029518659048'),
('37.840832', '-76.27383399999999'), ...
('38.976334', '-76.47350299999999'))


We'll want data like the following code snippet, where we have floats:


(((37.54901619777347, -76.33029518659048),
(37.840832, -76.273834)), ((37.840832, -76.273834), ...
((38.330166, -76.458504), (38.976334, -76.473503)))

Free download pdf