以下是一个简单的示例代码,展示了如何使用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函数指定自定义的排序规则

python 排序 代码

原文地址: http://www.cveoy.top/t/topic/ihfq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录