【python学习】基础篇-常用函数-sorted() 对可迭代对象进行排序

sorted()函数是Python中的内置函数,用于对可迭代对象进行排序操作。

它会返回一个新的已排序的列表,而不会修改原始的可迭代对象。

sorted()函数的基本语法如下:

python 复制代码
sorted(iterable, key=None, reverse=False)

参数说明:

iterable:表示要排序的可迭代对象,如列表、元组等。

key:可选参数,用于指定一个函数来确定排序的依据。该函数将作用于可迭代对象的每个元素上,并根据其返回值进行排序。默认为None,即按照元素本身的大小进行排序。

reverse:可选参数,用于指定排序的顺序。如果设置为True,则按降序排列;如果设置为False或不指定,则按升序排列。默认为False。

示例:

python 复制代码
# 对列表进行排序
numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出:[1, 2, 3, 4, 5]

# 对字符串进行排序
words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words)
print(sorted_words)  # 输出:['apple', 'banana', 'cherry']

# 按照元素长度进行排序
words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=len)
print(sorted_words)  # 输出:['apple', 'cherry', 'banana']

# 按照元素长度进行降序排序
words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=len, reverse=True)
print(sorted_words)  # 输出:['banana', 'cherry', 'apple']
相关推荐
寻星探路4 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly2024065 小时前
Bootstrap 警告框
开发语言
2601_949146536 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧6 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX6 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01036 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder6 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
执笔论英雄6 小时前
【大模型学习cuda】入们第一个例子-向量和
学习
wdfk_prog6 小时前
[Linux]学习笔记系列 -- [drivers][input]input
linux·笔记·学习
猫头虎7 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven