Python3中的sorted函数

参照http://blog.csdn.net/lanchunhui/article/details/50959390中的一些说法和例子。

sorted() 函数接口:


>>> help(sorted)
Help on built-in function sorted in module builtins:


sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.升序返回一个新的列表包含所有项目的迭代
    
    A custom key function can be supplied to customize the sort order, and the可以提供自定义key函数以自定义排序顺序。
    reverse flag can be set to request the result in descending order.可以设置反向标志以按降序返回结果。


参数 key 用于指定用于比较的对象,key 其实是一个函数,接收的参数是前面的可迭代对象(iterable)中的每一个元素

这里要注意的一点是,直接对字典对象迭代(也是sorted函数默认的做法)出来的元素不是 key-value 对,而是单独的key,最终的返回是由 key 构成的 list:

>>> dic={'b':3,'a':5,'c':9,'d':2}
>>> sorted(dic.items(), key=lambda x: x[1])
[('d', 2), ('b', 3), ('a', 5), ('c', 9)]
>>> L = [('d',2),('a',4),('b',3),('c',2)]
>>> sorted(L, key=lambda x:(x[1],x[0]))
[('c', 2), ('d', 2), ('b', 3), ('a', 4)]

>>> for t in dic.items():
	print(t)	
('b', 3)
('a', 5)
('c', 9)
('d', 2)

>>> for t in dic.items():
	print(t[1])	
3
5
9
2

例子:

 >>>nums=[19, 7, 8, 25]

>>> index = sorted(range(len(nums)), key = lambda i: nums[i])
>>> index
[1, 2, 0, 3]

返回结果:range(len(nums))排序后的结果。

key函数:输入是迭代对象中range(len(nums))中的每一个元素。

nums[i]:  按照nums[i]进行排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值