Python List sort()方法

Python List sort() method sorts the list elements in the natural ordering. The sorting happens in-place, so the list is modified.

Python List sort()方法以自然顺序对列表元素进行排序。 排序发生在原位,因此列表被修改。

Python has a built-in function – sorted() – which is used to create a sorted list from an iterable.

Python具有内置函数sorted() ,该函数用于从可迭代对象创建排序列表。

1. Python排序列表(自然顺序) (1. Python Sort List in Natural Order)

When we sort a list of numbers, the natural ordering is to sort them in the increasing order.

当我们对数字列表进行排序时,自然的排序是按照升序对它们进行排序。

numbers_list = [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]

print(f'Before sorting: {numbers_list}')

numbers_list.sort()

print(f'After sorting: {numbers_list}')

Output:

输出

Before sorting: [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]
After sorting: [1.0, 2.2, 3.4, 3.8, 4.1, 5.1]
Recommended Read: 推荐阅读Python f-strings Python f字符串

The default sorting is implemented for strings also. Here is a simple example to sort a list of strings.

默认排序也针对字符串实现。 这是一个对字符串列表进行排序的简单示例。

str_list = ['a', 'c', 'd', 'b', 'B', 'C', '1']
str_list.sort()
print(str_list)  # ['1', 'B', 'C', 'a', 'b', 'c', 'd']

2.以相反的顺序对列表进行排序 (2. Sorting a List in Reverse Order)

If you want the sorting to be done in the reversed order, pass the reverse argument as True. We can use this to sort a list of numbers in the descending order.

如果您希望以相反的顺序进行排序,请将reverse参数传递为True。 我们可以使用它来按降序对数字列表进行排序。

numbers_list = [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]

print(f'Before sorting: {numbers_list}')

numbers_list.sort(reverse=True)

print(f'After sorting: {numbers_list}')

Output:

输出

Before sorting: [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]
After sorting: [5.1, 4.1, 3.8, 3.4, 2.2, 1.0]

3.对嵌套列表进行排序 (3. Sorting a Nested List)

If we call the sort() function on a nested list, only the first elements from the list elements are used for the sorting. Let’s understand this with a simple example.

如果我们在嵌套列表上调用sort()函数,则仅将列表元素中的前几个元素用于排序。 让我们用一个简单的例子来理解这一点。

numbers = [[1, 2], [2, 1], [4, 3], [5, 2], [3, 3]]

print(f'Before sorting: {numbers}')

numbers.sort()

print(f'After sorting: {numbers}')

Output:

输出

Before sorting: [[1, 2], [2, 1], [4, 3], [5, 2], [3, 3]]
After sorting: [[1, 2], [2, 1], [3, 3], [4, 3], [5, 2]]

It’s clear that the sorting is performed based on the first element in the nested list.

显然,排序是基于嵌套列表中的第一个元素进行的。

But, sometimes we want to sort the nested list based on different elements position.

但是,有时我们想根据不同元素的位置对嵌套列表进行排序。

Let’s say the nested list contains information about a Persons’ name, age, and gender. Let’s see how to sort this nested list based on the age, which is the second element in the nested list.

假设嵌套列表包含有关人员姓名,年龄和性别的信息。 让我们看看如何根据年龄对嵌套列表进行排序,这是嵌套列表中的第二个元素。

def custom_key(people):
    return people[1]  # second parameter denotes the age


persons = [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alexa', 22, 'F']]

print(f'Before sorting: {persons}')

persons.sort(key=custom_key)

print(f'After sorting: {persons}')

Output:

输出:

Before sorting: [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alexa', 22, 'F']]
After sorting: [['Alexa', 22, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alice', 26, 'F']]

We are using the key argument to specify the element to be used for the sorting purpose. The custom_key function returns the key to sort the list.

我们使用key参数来指定要用于排序目的的元素。 custom_key函数返回用于对列表进行排序的键。

4.自定义逻辑对列表进行排序 (4. Custom Logic to Sort a List)

We can also implement your own logic to sort the list elements.

我们还可以实现自己的逻辑来对列表元素进行排序。

In the last example, we used the age as the key element to sort our list.

在最后一个示例中,我们使用年龄作为对列表进行排序的关键元素。

But there goes a saying, “Ladies first!”.

但是有一句话,“女士优先!”。

So, we want to sort our list in such a way that the female gender gets priority over the male. If the gender of two persons matches, the younger one gets a higher priority.

因此,我们希望对列表进行排序,以使女性优先于男性。 如果两个人的性别匹配,则年龄较小的人会获得更高的优先级。

So, we have to use the key argument in our sort function. But the compare function needs to be converted into a key.

因此,我们必须在我们的排序函数中使用key参数。 但是比较功能需要转换为键。

So, we need to import a library called functools. We will use the function cmp_to_key() to convert our compare function into a key.

因此,我们需要导入一个名为functools的库。 我们将使用功能cmp_to_key()将比较功能转换为键。

import functools


def compare_function(person_a, person_b):
    if person_a[2] == person_b[2]:  # if their gender become same
        return person_a[1] - person_b[1]  # return True if person_a is younger
    else:  # if their gender not matched
        if person_b[2] == 'F':  # give person_b first priority if she is female
            return 1
        else:  # otherwise give person_a first priority
            return -1


persons = [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 24, 'M'], ['Alexa', 22, 'F']]

print(f'Before sorting: {persons}')

persons.sort(key=functools.cmp_to_key(compare_function))

print(f'After sorting: {persons}')

Output:

输出:

Before sorting: [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 24, 'M'], ['Alexa', 22, 'F']]
After sorting: [['Alexa', 22, 'F'], ['Alice', 26, 'F'], ['Bob', 24, 'M'], ['Trudy', 25, 'M']]

The list is sorted based on the gender first. Then it’s sorted based on the age of the persons.

该列表首先基于性别进行排序。 然后根据人员的年龄进行排序。

5.排序对象列表 (5. Sorting a List of Objects)

The default sorting works on numbers and strings. But, it won’t work on the list of custom objects.

默认排序适用于数字和字符串。 但是,它不适用于自定义对象列表。

Let’s see what happens when we try to run the default sorting on a list of objects.

让我们看看当尝试在对象列表上运行默认排序时会发生什么。

class Employee:

    def __init__(self, n, a, gen):
        self.name = n
        self.age = a
        self.gender = gen

    def __str__(self):
        return f'Emp[{self.name}:{self.age}:{self.gender}]'

    # List uses __repr__, so overriding it to print useful information
    __repr__ = __str__


e1 = Employee('Alice', 26, 'F')
e2 = Employee('Trudy', 25, 'M')
e3 = Employee('Bob', 24, 'M')
e4 = Employee('Alexa', 22, 'F')

emp_list = [e1, e2, e3, e4]

print(f'Before Sorting: {emp_list}')

try:
    emp_list.sort()
except TypeError as te:
    print(te)

Output:

输出:

Before Sorting: [Emp[Alice:26:F], Emp[Trudy:25:M], Emp[Bob:24:M], Emp[Alexa:22:F]]
'<' not supported between instances of 'Employee' and 'Employee'

In this case, we have to mandatorily provide the key function to specify the objects’ field to be used for sorting.

在这种情况下,我们必须强制提供键函数来指定要用于排序的对象的字段。

# sorting based on age
def sort_by_age(emp):
    return emp.age


emp_list.sort(key=sort_by_age)
print(f'After Sorting By Age: {emp_list}')

Output:

输出:

After Sorting By Age: [Emp[Alexa:22:F], Emp[Bob:24:M], Emp[Trudy:25:M], Emp[Alice:26:F]]

We can also utilize the functools module to create custom sorting logic for the list elements.

我们还可以利用functools模块为列表元素创建自定义排序逻辑。

References: Official API Documentation

参考官方API文档

翻译自: https://www.journaldev.com/14504/python-sort-list

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值