# 示例代码:使用sorted函数对列表进行排序
# 定义一个包含整数的列表
numbers = [5, 2, 9, 1, 5, 6]
# 使用sorted函数对列表进行升序排序
sorted_numbers = sorted(numbers)
print("升序排序后的列表:", sorted_numbers)
# 使用sorted函数对列表进行降序排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print("降序排序后的列表:", sorted_numbers_desc)
# 定义一个包含字符串的列表
words = ["apple", "banana", "cherry", "date"]
# 使用sorted函数对字符串列表进行排序(按字母顺序)
sorted_words = sorted(words)
print("按字母顺序排序后的列表:", sorted_words)
# 使用sorted函数对字符串列表进行排序(按字符串长度)
sorted_words_by_length = sorted(words, key=len)
print("按字符串长度排序后的列表:", sorted_words_by_length)
# 解释说明:
# - sorted() 函数可以对任何可迭代对象进行排序,并返回一个新的已排序列表。
# - 参数 reverse=True 可以将排序结果反转为降序。
# - 参数 key 指定一个函数,该函数用于从每个元素中提取比较键。例如,key=len 表示按照字符串长度进行排序。
上一篇:python命令行
下一篇:python二进制转10进制
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站