python 字典排序 关于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‘]
关于字典序:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。