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

sorted函数python用法

作者:一抹淡影   发布日期:2025-08-28   浏览:87

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

# 1. 对数字列表进行排序
numbers = [5, 2, 9, 1, 7, 6, 3]
sorted_numbers = sorted(numbers)
print("原始数字列表:", numbers)
print("排序后的数字列表:", sorted_numbers)

# 2. 对字符串列表进行排序
words = ["banana", "apple", "cherry", "date"]
sorted_words = sorted(words)
print("原始字符串列表:", words)
print("排序后的字符串列表:", sorted_words)

# 3. 使用 key 参数自定义排序规则(按字符串长度排序)
words_by_length = sorted(words, key=len)
print("按长度排序后的字符串列表:", words_by_length)

# 4. 使用 reverse 参数进行降序排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print("降序排序后的数字列表:", sorted_numbers_desc)

# 5. 对包含元组的列表进行排序(按元组的第二个元素排序)
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print("按第二个元素排序后的元组列表:", sorted_pairs)

解释说明:

  • sorted() 函数可以对任何可迭代对象(如列表、元组、集合等)进行排序,并返回一个新的已排序列表。
  • key 参数允许我们指定一个函数,该函数用于从每个元素中提取比较键。例如,key=len 表示按字符串长度排序。
  • reverse 参数为 True 时,表示按降序排序,默认为 False 即升序排序。
  • 原始列表不会被修改,sorted() 返回的是一个新的列表。

上一篇:python的输入函数

下一篇:python telnetlib

大家都在看

python时间格式

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

python pypinyin

python的for i in range

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

Laravel 中文站