Chapter 13
These match built-in functions in other functional programming languages.
We don't really need to write these functions. There's a version available in the
operator module which describes these functions.
Here's some sample data we can work with:
year_cheese = [(2000, 29.87), (2001, 30.12), (2002, 30.6),
(2003, 30.66), (2004, 31.33), (2005, 32.62), (2006, 32.73),
(2007, 33.5), (2008, 32.84), (2009, 33.02), (2010, 32.92)]
This is the annual cheese consumption. We used this example in Chapter 2,
Introducing Some Functional Features and Chapter 9, More Itertools Techniques.
We can locate the data point with minimal cheese using the following commands:
min(year_cheese, key=snd)
(2000, 29.87)
The operator module gives us an alternative to pick particular elements from
a tuple. This saves us from using a lambda variable to pick the second item.
Instead of defining our own fst() and snd() functions, we can use the
itemgetter(0) and the itemgetter(1) parameters, as shown in the
following command:
from operator import *
max( year_cheese, key=itemgetter(1))
(2007, 33.5)
The itemgetter() function relies on the special method, getitem(), to pick
items out of a tuple (or list) based on their index position.
Getting named attributes when using higher-order functions
Let's look at a slightly different collection of data. Let's say we were working with
namedtuples instead of anonymous tuples. We have two ways to locate the range
of cheese consumption shown as follows:
from collections import namedtuple
YearCheese = namedtuple("YearCheese", ("year", "cheese"))
year_cheese_2 = list(YearCheese(*yc) for yc in year_cheese)
year_cheese_2