python模块operator对排序的辅助功能
一、介绍
该operator
模块导出一组与Python的内部运算符相对应的高效函数。例如,等同于表达式。函数名称是用于特殊类方法的函数名称; 为方便起见,还提供了没有前导和尾随的变体。operator.add(x, y)
x+y
__
这些函数属于执行对象比较,逻辑运算,数学运算,序列运算和抽象类型测试的类别。
模块特殊函数:都返回一个可调用对象,可以用于 map(), sorted(), itertools.groupby() 等接受一个函数对象作为参数的函数
operator.attrgetter(*attrs):返回对象的对应属性
operator.itemgetter(*items):返回对象对应位置的值,相当于 __getitem__() 方法
operator.methodcaller(name[, args...]):返回对象的对应方法函数,额外输入的 args 会作为此方法的默认参数
二、代码
import operator a = [1, 2, 3, 4, 5] b = operator.itemgetter(1) print(b(a)) e = {'E': 1, 'A': 2, 'B': 1, 'D': 3, 'C': 1} res = sorted(e.items(), key=operator.itemgetter(1), reverse=True) print(res) students = [ {"name": "maple", "age": 22, "score": 92}, {"name": "ffm", "age": 19, "score": 99}, {"name": "angel", "age": 23, "score": 82}, {"name": "tom", "age": 20, "score": 88}, {"name": "jerry", "age": 22, "score": 95} ] students_score = sorted(students, key=operator.itemgetter("score"), reverse=True) print(students_score) class Student: def __init__(self, name, id): self.name = name self.id = id def __repr__(self): return "(%s, %s)" % (self.name, self.id) students = [Student('maple', 167), Student('ffm', 288), Student('angel', 134), Student('tom', 111), Student('jerry', 101)] students_by_id = sorted(students, key=operator.attrgetter('id')) print(students_by_id)
#代码结果 2 [('D', 3), ('A', 2), ('E', 1), ('B', 1), ('C', 1)] [{'name': 'ffm', 'age': 19, 'score': 99}, {'name': 'jerry', 'age': 22, 'score': 95}, {'name': 'maple', 'age': 22, 'score': 92}, {'name': 'tom', 'age': 20, 'score': 88}, {'name': 'angel', 'age': 23, 'score': 82}] [(jerry, 101), (tom, 111), (angel, 134), (maple, 167), (ffm, 288)]