Python sorted() function returns a sorted list from the items in the iterable.

Python sorted()函数从iterable中的项目返回排序列表。

Python sorted()函数 (Python sorted() function)

Python sorted() function syntax is:

Python sorted()函数语法为:

sorted(iterable, *, key=None, reverse=False)

There are two optional arguments – key and reverse – which must be specified as keyword arguments.

有两个可选参数– key和reverse –必须指定为关键字参数。

  • iterable: elements from the iterable will be sorted. If key is not specified then natural sorting is used for the elements.iterable :将对iterable中的元素进行排序。 如果未指定键,则对元素使用自然排序。
  • key: specifies a function of one argument that is used to extract a comparison key from each list element.key :指定一个参数的函数,该函数用于从每个列表元素中提取比较键。
  • reverse: optional boolean argument. If specified as True then elements are sorted in reverse order.reverse :可选的布尔参数。 如果指定为True,则元素以相反的顺序排序。

Python sorted()字符串 (Python sorted() string)

String is iterable in Python, let’s see an example of using sorted() function with string argument.

字符串在Python中是可迭代的,让我们看一个使用带有字符串参数的sorted()函数的示例。

s = sorted('djgicnem')
print(s)

Output: ['c', 'd', 'e', 'g', 'i', 'j', 'm', 'n']

输出: ['c', 'd', 'e', 'g', 'i', 'j', 'm', 'n']

Python sorted()反向 (Python sorted() reverse)

Let’s see the sorted list when reversed is passed as True.

让我们看一下将反向传递为True时的排序列表。

s = sorted('azbyx', reverse=True)
print(s)

Output: ['z', 'y', 'x', 'b', 'a']

输出: ['z', 'y', 'x', 'b', 'a']

Python sorted()元组 (Python sorted() tuple)

s = sorted((1, 3, 2, -1, -2))
print(s)s = sorted((1, 3, 2, -1, -2), reverse=True)
print(s)

Output:

输出:

[-2, -1, 1, 2, 3]
[3, 2, 1, -1, -2]

Python sorted()键 (Python sorted() key)

Let’s say we want to sort a sequence of numbers based on their absolute value, we don’t care about their being positive or negative. We can achieve this by passing key=abs to sorted() function. Note that abs() is the built-in function that returns the absolute value of the number.

假设我们要根据数字的绝对值对数字序列进行排序,我们不在乎它们是正数还是负数。 我们可以通过将key=abs传递给sorted()函数来实现。 注意, abs()是返回数字绝对值的内置函数。

s = sorted((1, 3, 2, -1, -2), key=abs)
print(s)

Output: [1, -1, 2, -2, 3]

输出: [1, -1, 2, -2, 3]

Python排序列表 (Python sort list)

Let’s see some examples of using sorted() function with list.

让我们看看将listed()函数与list一起使用的一些示例。

s = sorted(['a', '1', 'z'])
print(s)s = sorted(['a', '1b', 'zzz'])
print(s)s = sorted(['a', '1b', 'zzz'], key=len)
print(s)s = sorted(['a', '1b', 'zzz'], key=len, reverse=True)
print(s)

Output:

输出:

['1', 'a', 'z']
['1b', 'a', 'zzz']
['a', '1b', 'zzz']
['zzz', '1b', 'a']

sorted()与list.sort() (sorted() vs list.sort())

  • sorted() function is more versatile because it works with any iterable argument.sorted()函数更具通用性,因为它可以与任何可迭代的参数一起使用。
  • Python sorted() function builds a new sorted list from an iterable whereas list.sort() modifies the list in-place.Python sorted()函数从可迭代对象构建新的排序列表,而list.sort()就地修改列表。

具有不同元素类型可迭代的sorted() (sorted() with iterable of different element types)

Let’s see what happens when we try to use sorted() function with iterable having different element types.

让我们看看当尝试使用具有不同元素类型的可迭代的sorted()函数时会发生什么。

s = sorted(['a', 1, 'x', -3])

Output:

输出:

TypeError: '<' not supported between instances of 'int' and 'str'

带自定义对象的sorted() (sorted() with custom objects)

We can use sorted() function to sort a sequence of custom object based on different types of criteria.

我们可以使用sorted()函数根据不同类型的条件对自定义对象序列进行排序。

Let’s say we have an Employee class defined as:

假设我们将Employee类定义为:

class Employee:id = 0salary = 0age = 0name = ''def __init__(self, i, s, a, n):self.id = iself.salary = sself.age = aself.name = ndef __str__(self):return 'E[id=%s, salary=%s, age=%s, name=%s]' % (self.id, self.salary, self.age, self.name)

Now we have a list of employee objects as:

现在,我们有了一个雇员对象列表:

e1 = Employee(1, 100, 30, 'Amit')
e2 = Employee(2, 200, 20, 'Lisa')
e3 = Employee(3, 150, 25, 'David')
emp_list = [e1, e2, e3]

Sort list of employees based on id

根据编号对员工排序

def get_emp_id(emp):return emp.idemp_sorted_by_id = sorted(emp_list, key=get_emp_id)
for e in emp_sorted_by_id:print(e)

Output:

输出:

E[id=1, salary=100, age=30, name=Amit]
E[id=2, salary=200, age=20, name=Lisa]
E[id=3, salary=150, age=25, name=David]

Sort list of employees based on age

根据年龄对员工列表进行排序

def get_emp_age(emp):return emp.ageemp_sorted_by_age = sorted(emp_list, key=get_emp_age)
for e in emp_sorted_by_age:print(e)

Output:

输出:

E[id=2, salary=200, age=20, name=Lisa]
E[id=3, salary=150, age=25, name=David]
E[id=1, salary=100, age=30, name=Amit]

摘要 (Summary)

Python sorted() function is guaranteed to be stable. It’s very powerful and allows us to sort a sequence of elements based on different keys.

Python sorted()函数保证稳定。 它非常强大,可以让我们根据不同的键对元素序列进行排序。

GitHub Repository.GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/23143/python-sorted-function

Python sorted()函数相关推荐

  1. Python sorted() 函数

    描述 sorted() 函数对所有可迭代的对象进行排序操作. sort 与 sorted 区别: sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作. list ...

  2. python sorted函数_Python 经典面试题 二

    1.简要描述Python的垃圾回收机制(garbage collection) Python中的垃圾回收是以引用计数为主,标记-清除和分代收集为辅. •引用计数:Python在内存中存储每个对象的引用 ...

  3. python向函数传递列表,【Python】向函数传递列表

    向函数传递列表 在实际使用中你会发现,向函数传递列表是比较实用的,这种列表可能包含名字.数字.可能更复杂的对象(字典) 假设向一个函数传递一堆水果,我们说出我们喜欢所有的水果 def Obj(frui ...

  4. Python sorted() 函数

    sorted 函数是 Python 中的内置函数,作用是对所有可迭代的对象进行排序. sort 与 sorted 区别: sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进 ...

  5. python中sorted函数逆序_Python中sorted函数的用法(转)

    [Python] sorted函数 我们需要对List.Dict进行排序,Python提供了两个方法 对给定的List L进行排序, 方法1.用List的成员函数sort进行排序,在本地进行排序,不返 ...

  6. python内置函数sorted(x)的作用是_Python内置filter与sorted函数

    Python内部提供了序列过滤函数 filter . 接收参数为 一个函数以及一个序列.函数依次作用于序列中的每一个元素,并根据返回值是True 或者 False 判断是否删除该元素. 样例如下 # ...

  7. sort函数pythonreverse_Python基础 7 ---- Python内置sort和sorted函数

    1 Python对数据的排序有两种方法,一种是容器内置的sort函数,另外一种利用sorted函数 2 对于sort函数我们不再进行讨论,只要研究一下sorted函数 3 sorted函数的原形sor ...

  8. python 排序函数 sort sorted 简介

    sort() 是Python列表的一个内置的排序方法,list.sort() 方法排序时直接修改原列表,返回None: sort() 是Python内置的一个排序函数,它会从一个迭代器返回一个排好序的 ...

  9. python sorted key=str.lower_Python——sorted()函数

    sorted()函数 1.  python内置的sorted()函数可以对 list 进行排序 >>> sorted([12,1,3,34,-4]) [-4, 1, 3, 12, 3 ...

  10. Python中的sorted函数以及operator.itemgetter函数

    from:Python中的sorted函数以及operator.itemgetter函数 operator.itemgetter函数 operator模块提供的itemgetter函数用于获取对象的哪 ...

最新文章

  1. scala recursive value x$5 needs type
  2. CentOS7 64位下MySQL5.7安装与配置
  3. Java程序调用ssh, scp, sftp
  4. Pycharm打开之后一直在扫描,进不去
  5. python 完全面向对象_史上最全的Python面向对象知识点疏理
  6. 为什么wait、notify、notifyAll方法定义在Object中而不是Thread类中
  7. 直线分割平面(动态规划递推)
  8. Spock 1.2 –轻松进行集成测试中的Spring Bean模拟
  9. scrollview嵌套listview 滑动事件冲突的解决方法
  10. 使用ANT编译项目报错 com.sun.image.codec.jpeg does not exist 解决方法
  11. 遍历进程并获取进程路径 - 回复 编程少年 的问题
  12. 如何防止SWF文件被反编译 如何防止SWF文件被反编译(2)
  13. 手机号码归属地数据库下载
  14. HTML5活动目的,完美活动策划方案指南(教你做有意思的H5方案)
  15. 2阶魔方矩阵matlab,matlab魔方矩阵
  16. IOS调用微信扫一扫scanQRCode报错the permission value is offline verifying
  17. 转载: 找不到MSVCR90.dll、Debug vs Release及cppLapack相关
  18. 快递管理系统 V2.0
  19. PX Deq Create send blkd
  20. 劳务员培训建筑八大员培训劳务员对劳务分包企业管理的建议

热门文章

  1. 傅里叶变换的终极解释下
  2. [转载] python学习笔记(三)- numpy基础:array及matrix详解
  3. [转载] python3基础:异常处理及python常见异常类型总结
  4. [转载] 浅析Java OutOfMemoryError
  5. 机器学习-数据科学库-day1
  6. CF 398 E(动态规划)
  7. elementUI 日期选择控件少一天的问题解决方法
  8. RPC 框架之 Goole protobuf
  9. [svc]centos7的服务治理-systemd
  10. iScroll API