Python 中sorted函数和operator.itemgetter函数

operator.itemgetter函数

原型:

operator. itemgetter ( item ) operator. itemgetter ( *items )

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example:

  • After f = itemgetter(2), the call f(r) returns r[2].
  • After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]).

注意:operator.itemgetter函数返回的是一个函数,该函数返回指定序号的值,通过该函数作用到对象上才能获取值

sorted函数

原型:sorted(iterable[cmp[key[reverse]]])
参数解释:

(1)iterable指定要排序的list或者iterable;

(2)cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

(3)key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly)。可能使用key=operator.itemgetter(1)比较多

(4)reverse参数,是一个bool变量,表示升序还是降序排列,默认为false(升序排列),定义为True时将按降序排列。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值