深入Python(1): 字典排序 关于sort()、reversed()、sorted()
一、Python的排序1、reversed()
这个很好理解,reversed英文意思就是:adj. 颠倒的;相反的;(判决等)撤销的
print list(reversed(['dream','a','have','I']))
#['I', 'have', 'a', 'dream']
2、让人糊涂的sort()与sorted()
在Python 中sorted是内建函数(BIF),而sort()是列表类型的内建函数list.sort()。
sorted()
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 Mutable Sequence Types).
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.
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).
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
#字符串排序使用是字典序,而非字母序
"""sorted()按照字典序排序"""
lis = ['a','c','z','E','T','C','b','A','Good','Tack']
print sorted(lis) #['A', 'C', 'E', 'Good', 'T', 'Tack', 'a', 'b', 'c', 'z']
关于字典序:
可参考百度百科。http://baike.baidu.com/view/4670107.htm
根据ASCII排,具体如下:
0-9(对应数值48-59);
A-Z(对应数值65-90);
a-z(对应数值97-122);
------------
标准序: 短在前,长在后,等长的依次比字母,
如to < up < cap < cat < too < two
页:
[1]