# 示例代码:使用sorted函数对列表进行排序
# 基本用法:对数字列表进行排序
numbers = [5, 2, 9, 1, 7]
sorted_numbers = sorted(numbers)
print("排序后的数字列表:", sorted_numbers) # 输出: 排序后的数字列表: [1, 2, 5, 7, 9]
# 对字符串列表进行排序
words = ["apple", "orange", "banana", "grape"]
sorted_words = sorted(words)
print("排序后的字符串列表:", sorted_words) # 输出: 排序后的字符串列表: ['apple', 'banana', 'grape', 'orange']
# 使用key参数自定义排序规则,例如按字符串长度排序
sorted_words_by_length = sorted(words, key=len)
print("按长度排序后的字符串列表:", sorted_words_by_length) # 输出: 按长度排序后的字符串列表: ['apple', 'grape', 'banana', 'orange']
# 使用reverse参数进行降序排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print("降序排序后的数字列表:", sorted_numbers_desc) # 输出: 降序排序后的数字列表: [9, 7, 5, 2, 1]
sorted() 函数用于对任何可迭代对象(如列表、元组等)进行排序,并返回一个新的已排序列表。sorted() 是按升序排序的。key 参数指定一个函数来作为排序的依据。例如,key=len 表示按字符串长度排序。reverse=True 参数可以将排序结果反转为降序排列。上一篇:redis python
下一篇:python的列表
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站