# 示例代码:使用 sorted() 函数对列表进行排序
# 定义一个包含数字的列表
numbers = [5, 2, 9, 1, 7, 6, 3]
# 使用 sorted() 对列表进行升序排序
sorted_numbers = sorted(numbers)
print("升序排序:", sorted_numbers)
# 使用 sorted() 对列表进行降序排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print("降序排序:", sorted_numbers_desc)
# 定义一个包含元组的列表,每个元组包含姓名和年龄
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
# 使用 sorted() 和 key 参数按年龄对列表进行排序
sorted_people_by_age = sorted(people, key=lambda x: x[1])
print("按年龄排序:", sorted_people_by_age)
# 使用 sorted() 和 key 参数按姓名长度对列表进行排序
sorted_people_by_name_length = sorted(people, key=lambda x: len(x[0]))
print("按姓名长度排序:", sorted_people_by_name_length)
sorted() 函数可以对任何可迭代对象(如列表、元组等)进行排序,默认是升序排序。reverse=True 参数可以用于将排序结果反转为降序。key 参数允许我们指定一个函数,该函数用于从每个元素中提取比较键。例如,我们可以根据元组中的第二个元素(即年龄)进行排序,或者根据字符串的长度进行排序。如果你需要进一步的帮助或有其他问题,请告诉我!
上一篇:python plot绘图
下一篇:python unique
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站