python中sorted

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值