sorted在Python中怎么使用

42次阅读
没有评论

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

在 Python 中,可以使用 sorted() 函数来对序列进行排序。
sorted()函数接受一个可迭代的对象作为参数,并返回一个新的已排序的列表。也可以使用 sorted() 函数对字典的键或值进行排序。
以下是一些示例:

  1. 对列表进行排序:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出: [1, 1, 2, 3, 4, 5, 5, 6, 9]
  1. 对字符串进行排序:
word = "hello"
sorted_word = sorted(word)
print(sorted_word)  # 输出: ['e', 'h', 'l', 'l', 'o']
  1. 对字典按键进行排序:
ages = {"Alice": 25, "Bob": 20, "Charlie": 30}
sorted_ages = sorted(ages)  # 按键排序
print(sorted_ages)  # 输出: ['Alice', 'Bob', 'Charlie']
  1. 对字典按值进行排序:
ages = {"Alice": 25, "Bob": 20, "Charlie": 30}
sorted_ages = sorted(ages.items(), key=lambda x: x[1])  # 按值排序
print(sorted_ages)  # 输出: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]

注意,sorted()函数返回一个新的已排序的列表,而不会修改原始的对象。如果想要在原地对列表进行排序,可以使用 list.sort() 方法。

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

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