Using NamedTuples to simplify item access in tuples
When we worked with tuples, we had to remember the positions as numbers. When we use a (r,g,b) tuple to represent a color, can we use "red" instead of zero, "green" instead of 1, and "blue" instead of 2?
Getting ready
Let's continue looking at items in recipes. The regular expression for parsing the string had three attributes: ingredient, amount, and unit. We used the following pattern with names for the various substrings:
r'(?P<ingredient>\w+):\s+(?P<amount>\d+)\s+(?P<unit>\w+)')
The resulting data tuple looked like this:
>>> item = match.groups()
('Kumquat', '2', 'cups')
While the matching between ingredient
, amount
, and unit
is pretty clear, using something like the following isn't ideal. What does "1" mean? Is it really the quantity?
>>> Fraction(item[1])
Fraction(2, 1)...