Functional Python Programming

(Wang) #1

Working with Collections


Finally, we'll look at the different-length list approach used by the zip() function:





list(zip((1, 2, 3), ('a', 'b')))
[(1, 'a'), (2, 'b')]





This result is debatable. Why truncate? Why not pad the shorter list with None values?
This alternate definition of zip() function is available in the itertools module as the
zip_longest() function. We'll look at this in Chapter 8, The Itertools Module.


Unzipping a zipped sequence


zip() mapping can be inverted. We'll look at several ways to unzip a collection
of tuples.


We can't fully unzip an iterable of tuples, since we might
want to make multiple passes over the data. Depending
on our needs, we might need to materialize the iterable
to extract multiple values.

The first way is something we've seen many times; we can use a generator function
to unzip a sequence of tuples. For example, assume that the following pairs are a
sequence object with two tuples:


p0= (x[0] for x in pairs)
p1= (x[1] for x in pairs)


This will create two sequences. The p0 sequence has the first element of each two
tuple; the p1 sequence has the second element of each two tuple.


Under some circumstances, we can use the multiple ssignment of a for loop to
decompose the tuples. The following is an example that computes the sum of
products:


sum(p0*p1 for for p0, p1 in pairs)


We used the for statement to decompose each two tuple into p0 and p1.


Flattening sequences


Sometimes, we'll have zipped data that needs to be flattened. For example, our input
might be a file that looks like this:


2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
...

Free download pdf