sort和sorted方法的使用

 

一、sorted()方法,接收两个参数,参数一: 可迭代对象,参数二:自定义字典的key,默认按升序排序

 

示例1:对列表进行排序:

 

 

nums_list = [2,7,8,3,6,1,5,4]

print(nums_list)
print(id(nums_list)) # 1442097549832


x = sorted(nums_list)
print(x)  # [1, 2, 3, 4, 5, 6, 7, 8]
print(id(x)) # 1442097550344 ,使用sorted排序后,会生成一个新列表
View Code

 

 

 

  

二、使用sort排序,使用匿名函数作为参数,对age进行排序

 

示例代码2:

 

students = [
    {
        'name':'hw',
        'age':19,
        'score':88
    },

    {
        'name':'lisa',
        'age':18,
        'score':100
    },
    {
        'name':'yy',
        'age':22,
        'score':58
    },
    {
        'name':'xx',
        'age':28,
        'score':39
    }
]

# 使用sort排序,使用匿名函数作为参数,对age进行排序
students.sort(key=lambda x:x['age'])
print(students)
View Code

 

  

运行结果:

[{'name': 'lisa', 'age': 18, 'score': 100}, {'name': 'hw', 'age': 19, 'score': 88}, {'name': 'yy', 'age': 22, 'score': 58}, {'name': 'xx', 'age': 28, 'score': 39}]

 

posted @ 2021-04-02 15:38  御姐玫瑰  阅读(153)  评论(0编辑  收藏  举报
levels of contents