本函数是实现对可迭代对象iterable进行排序。可选参数key是比较键的函数;reverse是表示是否反向排列对象里的项,是布尔值。
例子:
#sorted() print(sorted([5, 2, 3, 1, 4])) print(sorted({1: ‘D‘, 2: ‘B‘, 3: ‘B‘, 4: ‘E‘, 5: ‘A‘}, reverse = True)) print(sorted("This is a test string from Andrew".split(), key=str.lower)) student_tuples = [ (‘john‘, ‘A‘, 75), (‘jane‘, ‘B‘, 62), (‘dave‘, ‘B‘, 100), ] print(sorted(student_tuples, key=lambda student: student[2])) # 按年龄排序
结果输出如下:
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[‘a‘, ‘Andrew‘, ‘from‘, ‘is‘, ‘string‘, ‘test‘, ‘This‘]
[(‘jane‘, ‘B‘, 62), (‘john‘, ‘A‘, 75), (‘dave‘, ‘B‘, 100)]
蔡军生 QQ:9073204 深圳
Python标准库:内置函数sorted(iterable[, key][, reverse])
原文:http://blog.csdn.net/caimouse/article/details/45128443