August 2018
Intermediate to advanced
332 pages
9h 12m
English
Now that we have seen more about iterators, and introduced the itertools module, we can show you how one of the first examples of this chapter (the one for computing statistics about some purchases), can be dramatically simplified:
def process_purchases(purchases): min_, max_, avg = itertools.tee(purchases, 3) return min(min_), max(max_), median(avg)
In this example, itertools.tee will split the original iterable into three new ones. We will use each of these for the different kinds of iterations that we require, without needing to repeat three different loops over purchases.
The reader can simply verify that if we pass an iterable object as the purchases parameter, this one is traversed only once (thanks to the itertools.tee ...