在 Python 中,sorted() 函数用于对可迭代对象进行排序操作,并返回一个新的已排序的列表。以下是 sorted() 函数的用法示例:

# 对列表进行排序
numbers = [9, 5, 2, 7, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出 [1, 2, 5, 7, 9]

# 对字符串进行排序
string = 'hello'
sorted_string = sorted(string)
print(sorted_string)  # 输出 ['e', 'h', 'l', 'l', 'o']

# 对元组进行排序
tuple_numbers = (9, 5, 2, 7, 1)
sorted_tuple = sorted(tuple_numbers)
print(sorted_tuple)  # 输出 [1, 2, 5, 7, 9]

# 对字典进行排序
dictionary = {'b': 4, 'a': 2, 'c': 1, 'd': 3}
sorted_dictionary = sorted(dictionary)
print(sorted_dictionary)  # 输出 ['a', 'b', 'c', 'd']

# 自定义排序规则
numbers = [9, 5, 2, 7, 1]
sorted_numbers = sorted(numbers, reverse=True)  # 降序排列
print(sorted_numbers)  # 输出 [9, 7, 5, 2, 1]

在上述示例中,我们展示了 sorted() 函数的不同用法。

  • 首先,我们对列表、字符串、元组和字典进行排序,并使用 print() 函数输出排序后的结果。
  • 其次,我们展示了如何使用 reverse 参数来控制排序的顺序,reverse=True 表示降序排列。

需要注意的是,sorted() 函数返回一个新的已排序的列表,并不会修改原始列表或其他可迭代对象。

希望对你有帮助!如果有任何其他问题,请随时提问。

Python sorted() 函数详解:排序列表、字符串、元组和字典

原文地址: https://www.cveoy.top/t/topic/bu44 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录