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

python中sorted的用法

作者:绝朢╭ァ   发布日期:2025-09-30   浏览:26

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

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

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

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

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

# 5. 对对象列表进行排序(按对象的某个属性排序)
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", 25),
    Person("Charlie", 35)
]

# 按年龄排序
sorted_people = sorted(people, key=lambda person: person.age)
print("\n按年龄排序后的人列表:", sorted_people)

解释说明:

  • sorted() 是 Python 内置函数,用于返回一个已排序的新列表。
  • 默认情况下,sorted() 对列表中的元素按升序排列。
  • 可以通过 key 参数指定一个函数来控制排序规则。例如,按字符串长度或对象的某个属性排序。
  • reverse=True 参数可以将排序结果反转为降序。

上一篇:python &&

下一篇:python调用其他py文件模块

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

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

Laravel 中文站