import operator
1. operator.itemgetter
operator.itemgetter(1)
等价于
lambda x: x[1]
2. 实现多级排序
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
使用 itemgetter() 可指定多个排序规则,比如本例的 sort by grade then by age:
>>> sorted(students, key=operator.itemgetter(1, 2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
3. 与 functools 模块的搭配
http://www.wklken.me/posts/2013/08/18/python-extra-functools.html
functools.partial:分批传参数进来
其实现见下:
#args/keywords 调用partial时参数 def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) return func(*(args + fargs), **newkeywords) # list + list,[1, 2] + [3, 4] ⇒ [1, 2, 3, 4] #合并,调用原始函数,此时用了partial的参数 newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc
urlunquote_fixed_encode = functools.partial(urlunquote, encoding='latin1')
,当调用urlunquote_fixed_encode(args, *kargs)
时,相当于调用urlunquote(args, *kargs, encoding='latin1')
;partial(func, *args, **keywords) ⇒ 虽然返回的是 newfunc,仅仅是一个函数对象,但其更是一个闭包,保留着调用 partial 时传递进来的参数(位置型参数以及关键字参数),但调用 newfunc时,会进一步传递新的参数进来;