Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python中sorted函数的用法

作者:嗜神魔影   发布日期:2026-04-11   浏览:88

# 示例代码:使用sorted函数对列表进行排序

# 基本用法:对数字列表进行排序
numbers = [5, 2, 9, 1, 7]
sorted_numbers = sorted(numbers)
print("排序后的数字列表:", sorted_numbers)  # 输出: 排序后的数字列表: [1, 2, 5, 7, 9]

# 对字符串列表进行排序
words = ["apple", "orange", "banana", "grape"]
sorted_words = sorted(words)
print("排序后的字符串列表:", sorted_words)  # 输出: 排序后的字符串列表: ['apple', 'banana', 'grape', 'orange']

# 使用key参数自定义排序规则,例如按字符串长度排序
sorted_words_by_length = sorted(words, key=len)
print("按长度排序后的字符串列表:", sorted_words_by_length)  # 输出: 按长度排序后的字符串列表: ['apple', 'grape', 'banana', 'orange']

# 使用reverse参数进行降序排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print("降序排序后的数字列表:", sorted_numbers_desc)  # 输出: 降序排序后的数字列表: [9, 7, 5, 2, 1]

解释说明:

  • sorted() 函数用于对任何可迭代对象(如列表、元组等)进行排序,并返回一个新的已排序列表。
  • 默认情况下,sorted() 是按升序排序的。
  • 可以通过 key 参数指定一个函数来作为排序的依据。例如,key=len 表示按字符串长度排序。
  • reverse=True 参数可以将排序结果反转为降序排列。

上一篇:redis python

下一篇:python的列表

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站