Python sort从大到小排序面试题

在Python中,你可以使用内置的sorted()函数或者列表的sort()方法来对列表中的元素进行从大到小的排序。

使用sorted()函数:

numbers = 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5

sorted_numbers = sorted(numbers, reverse=True) # 设置reverse=True实现从大到小排序

print(sorted_numbers) # 输出: 9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1

使用列表的sort()方法:

numbers = 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5

numbers.sort(reverse=True) # 设置reverse=True实现从大到小排序

print(numbers) # 输出: 9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1

两种方法都可以实现从大到小的排序,sort()方法会直接修改原列表,而sorted()函数会返回一个新的排序后的列表,原列表不受影响。

相关推荐
星云穿梭15 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵15 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠21 小时前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780512 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫2 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试