python

sorted在Python中怎么使用

小亿
99
2023-09-21 19:44:40
栏目: 编程语言

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

0
看了该问题的人还看了