当前位置:   article > 正文

Python sorted与lambda表达式结合的用法_sorted lamda

sorted lamda

1. Python sorted()函数

1.1 描述

sorted() 函数是全局排序函数,对所有可迭代的对象进行排序操作,它不会修改原对象,而将排序后的结果作为函数的返回值。

sort 与 sorted 的区别:

sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

1.2 语法

sorted 语法:

sorted(iterable, key=None, reverse=False)
  • 1

参数说明:

  • iterable – 可迭代对象。
  • key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
  • reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

返回值:
返回排序后的对象

1.3 例子
# example1
nums = [2, 3, 0, 1, 5, 4]
sorted(nums)
print(nums)  # 没有改变原数组
  • 1
  • 2
  • 3
  • 4

输出:

[2, 3, 0, 1, 5, 4]

# example2
nums = [2, 3, 0, 1, 5, 4]
nums1 = sorted(nums)  # 升序
print(nums1)

nums2 = sorted(nums, reverse=True)  # 降序
print(nums2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

输出:

[0, 1, 2, 3, 4, 5]
[5, 4, 3, 2, 1, 0]

下面对 lambda 表达式单独进行讲解

2. sorted() 函数与 lambda 表达式结合

lambda 表达式是 Python 中一类特殊的定义函数的形式,使用它可以定义一个匿名函数。与其它语言不同,Python 的 lambda 表达式的函数体只能有单独的一条语句,也就是返回值表达式语句。

2.1 例子
2.1.1 使用 lambda 表达式对一维数组进行倒序排序
nums = [2, 3, 0, 1, 5, 4]
nums1 = sorted(nums, key=lambda x:x*-1)
print(nums1)
  • 1
  • 2
  • 3

输出:

[5, 4, 3, 2, 1, 0]

2.1.2 按照二维矩阵下标为 1 的列进行排序
matrix = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
ret = sorted(matrix, key=lambda x: x[1])
print(ret)
  • 1
  • 2
  • 3

输出:

[[7, 0], [5, 0], [7, 1], [6, 1], [5, 2], [4, 4]]

2.1.3 对字典数组的某一关键字进行排序
# 以 age 的降序进行排序
array = [{"age": 20, "name": "a"}, {"age": 25, "name": "b"}, {"age": 10, "name": "c"}]
array = sorted(array, key=lambda x:x["age"], reverse=True)
# 上一句等同于
# array = sorted(array, key=lambda x:-x["age"])
print(array)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

输出:

[{‘age’: 25, ‘name’: ‘b’}, {‘age’: 20, ‘name’: ‘a’}, {‘age’: 10, ‘name’: ‘c’}]

2.1.4 先按照成绩降序排序,相同成绩的按照名字升序排序
d1 = [{'name': 'alice', 'score': 38}, {'name': 'bob', 'score': 18}, {'name': 'darl', 'score': 28}, {'name': 'christ', 'score': 28}]
l = sorted(d1, key=lambda x:(-x['score'], x['name']))
print(l)
  • 1
  • 2
  • 3

输出:

[{‘name’: ‘alice’, ‘score’: 38}, {‘name’: ‘christ’, ‘score’: 28}, {‘name’: ‘darl’, ‘score’: 28}, {‘name’: ‘bob’, ‘score’: 18}]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/754617
推荐阅读
相关标签
  

闽ICP备14008679号