python怎么排序

Python

1个回答

写回答

大为为1991

2023-03-28 08:42

+ 关注

Python
Python

Python中,您可以使用以下方法排序:

1. sort()方法:这是Python中最常用的排序方法,它可以对列表(或元组)进行排序。

例子:

Apple
Apple

Python

fruits = ['Apple', 'banana', 'orange', 'kiwi', 'pear']

fruits.sort()

print(fruits)

输出:

['Apple', 'banana', 'kiwi', 'orange', 'pear']

2. sorted()函数:它可以对任何可迭代的对象排序,包括列表、元组、字符串和字典。

例子:

Python

numbers = [8, 4, 2, 9, 5]

sorted_numbers = sorted(numbers)

print(sorted_numbers)

words = ['cat', 'dog', 'bird', 'elephant']

sorted_words = sorted(words)

print(sorted_words)

输出:

[2, 4, 5, 8, 9]

['bird', 'cat', 'dog', 'elephant']

3. 按键排序:需要对字典进行排序时,可以使用按键排序。

例子:

Python

ages = {'bob': 42, 'alice': 23, 'charlie': 33}

sorted_ages = sorted(ages)

print(sorted_ages)

输出:

['alice', 'bob', 'charlie']

4. 自定义排序:您可以使用lambda函数来指定自定义排序。

例子:

Python

students = [('John', 'A', 15), ('Victoria', 'C', 12), ('Tyler', 'B', 18)]

sorted_students = sorted(students, key=lambda x: x[2])

print(sorted_students)

输出:

[('Victoria', 'C', 12), ('John', 'A', 15), ('Tyler', 'B', 18)]

这些是Python中常用的排序方法,您可以根据您的特定需求选择其中之一。

举报有用(17分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号