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

sort函数python

作者:酷帥男爵   发布日期:2025-07-29   浏览:38

# 使用 Python 的 sort 函数对列表进行排序

# 示例代码 1: 对数字列表进行排序
numbers = [5, 2, 9, 1, 7, 6, 3]
numbers.sort()  # 直接修改原列表,按升序排序
print(numbers)  # 输出: [1, 2, 3, 5, 6, 7, 9]

# 示例代码 2: 对字符串列表进行排序
words = ["banana", "apple", "cherry", "date"]
words.sort()  # 按字母顺序排序
print(words)  # 输出: ['apple', 'banana', 'cherry', 'date']

# 示例代码 3: 使用自定义排序规则 (按字符串长度排序)
words.sort(key=len)  # 按字符串长度排序
print(words)  # 输出: ['date', 'apple', 'banana', 'cherry']

# 示例代码 4: 按降序排序
numbers.sort(reverse=True)  # 按降序排序
print(numbers)  # 输出: [9, 7, 6, 5, 3, 2, 1]

解释说明:

  • sort() 是 Python 列表对象的一个方法,用于对列表中的元素进行排序。
  • 默认情况下,sort() 会对列表进行升序排序。
  • 可以通过传递 key 参数来自定义排序规则,例如按字符串长度排序。
  • 通过传递 reverse=True 参数可以实现降序排序。

上一篇:python int函数

下一篇:python中lambda用法

大家都在看

python时间格式

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

python的for i in range

npm config set python

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

Laravel 中文站