Python 排序教程:列表、字典和字符串排序代码示例
以下是一个简单的示例代码,展示了如何使用 Python 进行排序:
# 使用 sorted 函数对列表进行排序
numbers = [5, 2, 9, 1, 7]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出 [1, 2, 5, 7, 9]
# 使用 sort 方法对列表进行原地排序
numbers = [5, 2, 9, 1, 7]
numbers.sort()
print(numbers) # 输出 [1, 2, 5, 7, 9]
# 对字典进行排序
students = [
{'name': 'Alice', 'age': 20},
{'name': 'Bob', 'age': 19},
{'name': 'Carol', 'age': 21}
]
sorted_students = sorted(students, key=lambda student: student['age'])
print(sorted_students) # 输出 [{'name': 'Bob', 'age': 19}, {'name': 'Alice', 'age': 20}, {'name': 'Carol', 'age': 21}]
# 对字符串进行排序
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words)
print(sorted_words) # 输出 ['apple', 'banana', 'cherry', 'date']
以上代码演示了如何使用 sorted 函数对列表进行排序,使用 sort 方法对列表进行原地排序,以及如何对字典和字符串进行排序。排序时,可以使用 lambda 函数指定自定义的排序规则。
原文地址: https://www.cveoy.top/t/topic/pZu6 著作权归作者所有。请勿转载和采集!