关于sorted函数的应用测试

# -*- coding: utf-8 -*-
"""
sorted( iterable[, cmp[, key[, reverse]]])

Return a new sorted list from the items in iterable.
The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section 3.6.4).

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())"

key specifies a function of one argument that is used to extract a comparison key from each list element: "key=str.lower"

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

"""

#iterable:是可迭代类型类型;
#cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项;
#key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;
#reverse:排序规则. reverse = True 或者 reverse = False,有默认值。
#返回值:是一个经过排序的可迭代类型,与iterable一样。
 
#一般来说,cmp和key可以使用lambda表达式。

test_list = {}
test_list[9]    = [19,  29,9,6,29]
test_list[56]   = [39,  49,9,9,2349]
test_list[222]  = [649, 59,9,9,59]
test_list[666]  = [6429,69,9,6,229]
test_list[2234] = [2239,79,9,6,29]
test_list[3]    = [97,  89,9,9,3339]
test_list[2]    = [99,  89,9,9,3339]

print test_list

#输出结果:
#{
#2: [99, 89, 9, 9, 3339],
#3: [97, 89, 9, 9, 3339],
#9: [19, 29, 9, 6, 29],
#56: [39, 49, 9, 9, 2349],
#666: [6429, 69, 9, 6, 229],
#2234: [2239, 79, 9, 6, 29],
#222: [649, 59, 9, 9, 59]
#}
#肯定key值是不相同的
l = sorted(test_list.items(), key = lambda d: d[1][4] ,reverse = 1 )
#每个d为(2, [99, 89, 9, 9, 3339])
#所以d[1] 为[99, 89, 9, 9, 3339]
#那么d[1][4] 为 3339
# reverse = 1 为进行升序排列;为0则进行降序排列
#经过这样的排列之后,新的字典为
print l
#输出结果:
#[
#(2, [99, 89, 9, 9, 3339]),
#(3, [97, 89, 9, 9, 3339]),
#(56, [39, 49, 9, 9, 2349]),
#(666, [6429, 69, 9, 6, 229]),
#(222, [649, 59, 9, 9, 59]),
#(9, [19, 29, 9, 6, 29]),
#(2234, [2239, 79, 9, 6, 29])
#]
print l[0]
#(2, [99, 89, 9, 9, 3339])
print l[0][0], "-->",l[0][1][0]
#2 --> 99
print l[0][1], "-->",l[0][1][4]
#[99, 89, 9, 9, 3339] --> 3339

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值