Linux 拨号vps windows公众号手机端

sorted在Python中怎么使用

lewis 7年前 (2018-06-02) 阅读数 6 #程序编程
文章标签 python

在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()方法。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门