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 = 0
salary = 0
age = 0
name = ''
def __init__(self, i, s, a, n):
self.id = i
self.salary = s
self.age = a
self.name = n
def __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.id
emp_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.age
emp_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()函数保证稳定。 它非常强大,可以让我们根据不同的键对元素序列进行排序。
Reference: Official Documentation
参考: 官方文档
翻译自: https://www.journaldev.com/23143/python-sorted-function