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

pythonsorted函数用法

作者:ら非你不取丶   发布日期:2026-04-27   浏览:61

# 示例代码:使用 Python 的 sorted 函数

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

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

# 使用 reverse 参数进行降序排序
sorted_numbers_descending = sorted(numbers, reverse=True)
print(sorted_numbers_descending)  # 输出: [9, 6, 5, 5, 2, 1]

# 对对象列表进行排序,使用 lambda 表达式作为 key 函数
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f'{self.name} ({self.age})'

people = [
    Person('Alice', 30),
    Person('Bob', 24),
    Person('Charlie', 35)
]

sorted_people_by_age = sorted(people, key=lambda person: person.age)
print(sorted_people_by_age)  # 输出: [Bob (24), Alice (30), Charlie (35)]

解释说明:

  1. 基本用法sorted() 函数可以对任何可迭代对象(如列表)进行排序,默认是升序排列。
  2. key 参数:通过 key 参数可以指定一个函数,用于从每个元素中提取比较的关键信息。例如,按字符串长度排序时,key=len 表示以字符串的长度作为排序依据。
  3. reverse 参数:通过设置 reverse=True 可以实现降序排序。
  4. 自定义对象排序:对于包含自定义对象的列表,可以通过 lambda 表达式或其他函数来指定排序的关键字段。

上一篇:python 命令行

下一篇:python定义字典

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python的assert基本用法

python开发windows应用程序

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

Laravel 中文站