欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > Python sorted()方法

Python sorted()方法

2025/3/26 6:32:34 来源:https://blog.csdn.net/qq_38830593/article/details/139812599  浏览:    关键词:Python sorted()方法

sorted() 是Python中的一个内置函数,用于对可迭代对象进行排序。它返回一个新的已排序的列表,而不会修改原始的可迭代对象。sorted() 函数的基本语法如下:

sorted(iterable, key=None, reverse=False)

参数解释:

  • iterable:必需,需要排序的可迭代对象,如列表、元组、字符串、字典等。
  • key:可选,一个函数,用于从每个元素中提取一个用于比较的键。这个函数应该接受一个参数并返回一个用于排序的键。默认值为 None,表示直接比较元素本身。
  • reverse:可选,一个布尔值,如果设置为 True,则排序结果将是降序。默认值为 False,表示升序排序。

示例

  1. 对列表进行升序排序:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  
# 输出: [1, 1, 2, 3, 4, 5, 6, 9]
  1. 对列表进行降序排序:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)  
# 输出: [9, 6, 5, 4, 3, 2, 1, 1]
  1. 使用 key 参数进行自定义排序:
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=len)
print(sorted_words)  
# 输出: ['date', 'apple', 'banana', 'cherry']

在这个例子中,key=len 表示按照字符串的长度进行排序。

  1. 结合 keyreverse 参数进行复杂排序:
students = [{'name': 'John', 'age': 20},{'name': 'Jane', 'age': 18},{'name': 'Doe', 'age': 20}
]sorted_students = sorted(students, key=lambda student: (-student['age'], student['name']))
print(sorted_students)

在这个例子中,key=lambda student: (-student['age'], student['name']) 表示首先按照年龄的负数进行排序(即年龄降序),如果年龄相同,则按照名字进行排序(即名字升序)。

输出结果将是:

[{'name': 'John', 'age': 20}, {'name': 'Doe', 'age': 20}, {'name': 'Jane', 'age': 18}]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词