sorted在Python中怎么使用

757
2023/10/14 19:44:40
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python怎么从列表中提取数据