# -*- 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
关于sorted函数的应用测试
最新推荐文章于 2024-07-23 21:10:46 发布