5

operator itemgetter 使用

 1 year ago
source link: https://blog.51cto.com/u_14967494/5938934
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

operator模块

能替代从序列中取出元素或读取对象属性的 lambda 表达式: itemgetter 和 attrgetter 其实会自行构建函数。
作用
根据元组的某个字段给元组列表排序。itemgetter(1) 的作用与 lambda fields: fields[1] 一样: 创建一个接受集合的函数, 返回索引位 1 上的元素

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 item in sorted(metro_data, key=itemgetter(1))
    print(item)
# 等同下方
for item in sorted(metro_data, key=lambda x: x[1]):
    print(item)
# 多个参数

cc_name = itemgetter(1, 0)
for item in metro_data:
    print(cc_name(item))

itemgetter 使用 [] 运算符, 因此它不仅支持序列, 还支持映射和任何实现 getitem 方法的类

from random import randint

map_data = [{'id': randint(1, 5), 'age': randint(16, 18)} for _ in range(10)]

# lambda
sorted(map_data, key=lambda x: (x['id'], x['age']))
# itemgetter
sorted(map_data, key=itemgetter('id', 'age'))
# 都可以完成 序列map_data首选根据id排序。id相同根据age 排序。reverse 默认为false 升序

映射案例是一次 北京 python后端开发工程师面试题。这里提供了两个方法


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK