python的sorted函数如何使用

40次阅读
没有评论

共计 954 个字符,预计需要花费 3 分钟才能阅读完成。

sorted 函数用于对可迭代对象进行排序。它接受一个可迭代对象作为输入,并返回一个新的已排序的列表。

sorted 函数的基本语法如下所示:

sorted(iterable, key=None, reverse=False)

其中:

  • iterable:表示要排序的可迭代对象,例如列表、元组、字符串等。
  • key:表示一个可调用对象(函数),用于为每个元素提供一个排序依据。可选参数,默认值为 None。
  • reverse:表示是否按照降序排列。可选参数,默认值为 False,表示按照升序排列。

下面是一些示例:

  1. 对列表进行排序,默认为升序排列:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
  1. 对字符串进行排序,按照字母的顺序:
message = "hello world"
sorted_message = sorted(message)
print(sorted_message)  # 输出:[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
  1. 使用 key 参数,按照元素的绝对值进行排序:
numbers = [3, -1, 4, -1, 5, -9, 2, -6, 5, 3]
sorted_numbers = sorted(numbers, key=abs)
print(sorted_numbers)  # 输出:[-1, -1, 2, 3, 3, 4, 5, 5, -6, -9]
  1. 使用 reverse 参数,按照降序排列:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)  # 输出:[9, 6, 5, 5, 4, 3, 3, 2, 1, 1]

这些只是 sorted 函数的一些基本用法,根据需要可以结合自定义的 key 函数进行更复杂的排序操作。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计954字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)