itemgetter 的常见用途:
根据元组的某个字段(index)给元组列表排序。
attrgetter的常见用途:
根据元组的某个字段(key)给元组列表排序,支持嵌套。
例:使用 itemgetter 排序一个元组列表
metro_data = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
from operator import itemgetter
for city in sorted(metro_data,key=itemgetter(1)):
print(city)#1
cc_name = itemgetter(1,0)
for city in metro_data:
print(cc_name(city))#2
输出:
1.
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833))
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889))
('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
('Mexico City', 'MX', 20.142, (19.433333, -99.133333))
('New York-Newark', 'US', 20.104, (40.808611, -74.020386))
2.
('JP', 'Tokyo')
('IN', 'Delhi NCR')
('MX', 'Mexico City')
('US', 'New York-Newark')
('BR', 'Sao Paulo')
解析:
itemgetter(1) 的作用与 lambda fields:fields[1] 一样: 创建一个接受集合的函数, 返回索引位 1 上的元素。
如果把多个参数传给 itemgetter, 它构建的函数会返回提取的值构成的元组。
例:显示城市和维度,根据维度排序
from collections import namedtuple
metro_data = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
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]
from operator import attrgetter
name_lat = attrgetter('name', 'coord.lat')
for city in sorted(metro_areas,key=attrgetter('coord.lat')):
print(name_lat(city))
输出:
('Sao Paulo', -23.547778)
('Mexico City', 19.433333)
('Delhi NCR', 28.613889)
('Tokyo', 35.689722)
('New York-Newark', 40.808611)
解析:
如果把多个属性名传给 attrgetter, 它也会返回提取的值构成的元组。key=attrgetter(‘coord.lat’)可以加入key=attrgetter(‘coord.lat’,‘coord.long’)当维度相同时比较经度。