📜  如何在Python对一组值进行排序?(1)

📅  最后修改于: 2023-12-03 14:52:52.003000             🧑  作者: Mango

如何在Python对一组值进行排序?

在Python中,我们可以使用内置的sorted()函数或.sort()方法来对一组值进行排序。这两种方法可以用于对数字、字符串和自定义对象等进行排序。

1. 使用sorted()函数进行排序

sorted()函数返回一个新的已排序的列表,而不会修改原始列表。它的基本语法如下:

sorted(iterable, key=key, reverse=reverse)
  • iterable:要排序的可迭代对象,如列表、元组、字符串等。
  • key(可选):指定一个用于排序的函数,可以根据该函数返回的值来进行排序。
  • reverse(可选):默认为False,表示升序排列;设置为True时,表示降序排列。

下面是几个示例:

对数字列表进行排序

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)

print(sorted_numbers)  # Output: [1, 1, 2, 3, 4, 5, 6, 9]

对字符串列表进行排序

fruits = ["apple", "banana", "cherry", "durian"]
sorted_fruits = sorted(fruits)

print(sorted_fruits)  # Output: ['apple', 'banana', 'cherry', 'durian']

根据自定义规则对对象列表进行排序

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [
    Person("Alice", 25),
    Person("Bob", 18),
    Person("Charlie", 32)
]

sorted_people = sorted(people, key=lambda p: p.age)

for person in sorted_people:
    print(f"{person.name} - {person.age}")

# Output:
# Bob - 18
# Alice - 25
# Charlie - 32
2. 使用.sort()方法进行排序

另一种常用的排序方法是使用列表的.sort()方法。这个方法会修改原始列表,而不会返回一个新列表。它的基本语法如下:

list.sort(key=key, reverse=reverse)

keyreverse的作用与sorted()函数中的相同。以下是一个使用.sort()方法的示例:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()

print(numbers)  # Output: [1, 1, 2, 3, 4, 5, 6, 9]

同样,你可以根据自定义规则对对象列表进行排序:

people = [
    Person("Alice", 25),
    Person("Bob", 18),
    Person("Charlie", 32)
]

people.sort(key=lambda p: p.age)

for person in people:
    print(f"{person.name} - {person.age}")

# Output:
# Bob - 18
# Alice - 25
# Charlie - 32

以上就是在Python中对一组值进行排序的两种常用方法。无论是使用sorted()函数还是.sort()方法,都可以根据不同的需求对列表进行排序。