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

sorted函数python

作者:嗜血苍狼   发布日期:2025-04-30   浏览:100

# 使用 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: 按照字符串长度进行排序
words_by_length = sorted(words, key=len)
print("按长度排序后的列表:", words_by_length)

# 示例 4: 按照自定义规则排序(例如,按照单词的最后一个字母排序)
def last_letter(word):
    return word[-1]

words_by_last_letter = sorted(words, key=last_letter)
print("按最后一个字母排序后的列表:", words_by_last_letter)

# 示例 5: 反向排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print("降序排序后的列表:", sorted_numbers_desc)

解释说明:

  • sorted() 函数用于对可迭代对象(如列表、元组等)进行排序,并返回一个新的已排序列表。
  • key 参数允许我们指定一个函数,该函数将应用于每个元素以确定排序顺序。
  • reverse 参数为 True 时,表示按降序排序,默认是升序。

上一篇:python列表

下一篇:python range函数

大家都在看

python时间格式

python ord和chr

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

python中list代表什么

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

Laravel 中文站