# 示例代码:使用 sorted 函数对列表进行排序
# 1. 对数字列表进行排序
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print("原始数字列表:", numbers)
print("排序后的数字列表:", sorted_numbers)
# 2. 对字符串列表进行排序
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words)
print("\n原始字符串列表:", words)
print("排序后的字符串列表:", sorted_words)
# 3. 使用 key 参数自定义排序规则(按字符串长度排序)
words_by_length = sorted(words, key=len)
print("\n按长度排序后的字符串列表:", words_by_length)
# 4. 使用 reverse 参数进行降序排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print("\n降序排序后的数字列表:", sorted_numbers_desc)
# 5. 对对象列表进行排序(按对象的某个属性排序)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"{self.name} ({self.age})"
people = [
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 35)
]
sorted_people_by_age = sorted(people, key=lambda person: person.age)
print("\n按年龄排序后的人名单:")
for person in sorted_people_by_age:
print(person)
sorted()
是 Python 内置函数,用于对可迭代对象进行排序,默认情况下会返回一个新的已排序列表,而不会修改原列表。key
参数可以指定一个函数,该函数用于从每个元素中提取比较键。例如,按字符串长度或对象的某个属性进行排序。reverse
参数为 True
时,表示按降序排序;默认为 False
,即升序排序。上一篇:python 遍历文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站