sorted在Python中怎么使用

   2025-02-21 2420
核心提示:在Python中,可以使用sorted()函数来对序列进行排序。sorted()函数接受一个可迭代的对象作为参数,并返回一个新的已排序的列表。

在Python中,可以使用sorted()函数来对序列进行排序。

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

以下是一些示例:

对列表进行排序:
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]
对字符串进行排序:
word = "hello"sorted_word = sorted(word)print(sorted_word)  # 输出: ['e', 'h', 'l', 'l', 'o']
对字典按键进行排序:
ages = {"Alice": 25, "Bob": 20, "Charlie": 30}sorted_ages = sorted(ages)  # 按键排序print(sorted_ages)  # 输出: ['Alice', 'Bob', 'Charlie']
对字典按值进行排序:
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()方法。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言