sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
iterable为可迭代对象,key默认为None reverse默认为False升序排列 ,为True降序排列,后两项可以忽略默认升序
返回值为一个列表,成员为元组,行如:[(key, val),(key, val)...]
sort(key,reverse):列表类型的方法对原列表进行排序无返回值None,只有排序的动作
sort() takes at most 2 arguments,参数可忽略默认为升序
示例:
help(sorted)
L = [1, 5, 2, 4, 3]
L1 = sorted(L)
L2 = sorted(L, key=None, reverse=False)
L3 = sorted(L, key=None, reverse=True)
print(L1)
print(L2)
print(L3)
print(L)
print(L.sort(key=None,reverse=False))
print(L)
print("")
dic = {55: 5, 44: 4, 22: 2, 33: 3, 11: 1}
dic_item = dic.items() # 【key,value组成的元组组成的列表】[(key, val),(key, val),...]
dic_L1 = sorted(dic) # 【直接排序字典得到的是key值排序的列表】[key,key,...]
dic_L2 = sorted(dic_item) # 【key,value组成的元组组成的列表按照key值对列表排序并返回】
dic_L3 = sorted(dic_item, key=None, reverse=False) # 后两项可以忽略
dic1 = {}
for x in dic_L3:
dic1[x[0]] = x[1]
print(dic_item)
print(dic_L1)
print(dic_L2)
print(dic_L3)
print(dic1)
结果:
D:\mypy\venv\Scripts\python.exe D:/mypy/sorted.py
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[1, 5, 2, 4, 3]
None
[1, 2, 3, 4, 5]
dict_items([(55, 5), (44, 4), (22, 2), (33, 3), (11, 1)])
[11, 22, 33, 44, 55]
[(11, 1), (22, 2), (33, 3), (44, 4), (55, 5)]
[(11, 1), (22, 2), (33, 3), (44, 4), (55, 5)]
{11: 1, 22: 2, 33: 3, 44: 4, 55: 5}
Process finished with exit code 0