Python sorted()函数

时间:2020-02-23 14:43:20  来源:igfitidea点击:

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

Python sorted()函数

Python sorted()函数语法为:

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

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

  • 可迭代:可迭代的元素将被排序。
    如果未指定键,则对元素使用自然排序。

  • key:指定一个参数的函数,该函数用于从每个列表元素中提取比较键。

  • 反向:可选的布尔参数。
    如果指定为True,则元素以相反的顺序排序。

Python sorted()字符串

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

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

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

Python sorted()反向

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

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

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

Python sorted()元组

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

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

输出:

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

Python sorted()键

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

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

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

Python排序列表

让我们来看一些在列表中使用sorted()函数的示例。

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)

输出:

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

sorted()与list.sort()

  • sorted()函数具有更多的通用性,因为它可以与任何可迭代的参数一起使用。

  • Python sorted()函数从可迭代对象构建新的排序列表,而list.sort()就地修改列表。

具有不同元素类型可迭代的sorted()

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

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

输出:

TypeError: '<' 不支持 between instances of 'int' and 'str'

带自定义对象的sorted()

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

假设我们将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)

现在,我们有一个雇员对象列表,如下所示:

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

根据编号对员工排序

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)

输出:

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]

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

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)

输出:

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]