函数名:sorted()
作用:对迭代对象进行排序(细节见代码)
调用方法:sorted(iterable, *, key=None, reverse=False)
参数:
iterable:任何可迭代的对象,列表,字符串,字典
key:可调用一个函数,用来作为排序的标准
reverse:是否反转(倒序)
官方解释:
sorted(iterable, *, key=None, reverse=False)
Return a new sorted list from the items in iterable.
Has two optional arguments which must be specified as keyword arguments.
key
specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, 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.
Use functools.cmp_to_key() to convert an old-style cmp function to a key function.
The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade)
个人理解举例:
lt = [1, 3, 2]
print(sorted(lt))#[1, 2, 3]
print(sorted(lt, reverse=True))#[3, 2, 1]
lt.sort()#[1, 2, 3]
"""
说明:lt.sort()方法只适用于列表操作,
是列表的专有内置函数,而sorted()函数
是Python内置函数,不单单可以作用于列表,任何迭代对象
皆可,如下
"""
s = "321"
print(sorted(s))#["1", "2", "3"],此例也说明sorted()函数返回值是一个列表
d = {3: "c", 2: "b", 1: "a"}
print(sorted(d))#[1, 2, 3],会将字典中的键,整理出来,作为列表返回
#此例对key参数用法做简单解释
print(sorted("This is a test string from Andrew".split(), key=str.lower))
"""
输出如下:
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
解释如下:
首先将字符串以空格字符,作为分割,遇到空格字符,就分为一个单独的字符串
然后排序,但是key参数的设置,意为在排序过程中,遇到大小写时
小写优先
如不设置,大写会优先的
"""