Attrgetter.py

>>> from collections import namedtuple >>> LatLong = namedtuple('LatLong', 'lat long') # >>> Metropolis = namedtuple('Metropolis', 'name cc pop coord') # >>> metro_areas = [Metropolis(name, cc, pop, LatLong(lat, long)) # ... for name, cc, pop, (lat, long) in metro_data] >>> metro_areas[0] Metropolis(name='Tokyo', cc='JP', pop=36.933, coord=LatLong(lat=35.689722, long=139.691667)) >>> metro_areas[0].coord.lat # 35.689722 >>> from operator import attrgetter >>> name_lat = attrgetter('name', 'coord.lat') # >>> >>> for city in sorted(metro_areas, key=attrgetter('coord.lat')): # ... print(name_lat(city)) # ...
Demo of attrgetter to process a previously defined list of namedtuple called metro_data

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.