Python中的sorted()函数如何使用?
发布时间:2023-07-04 06:48:38
Python中的sorted()函数用于对可迭代对象进行排序。它可以接受多个参数,包括可迭代对象和关键字参数。
基本语法如下:
sorted(iterable, *, key=None, reverse=False)
其中,iterable参数是待排序的可迭代对象,例如列表、元组或字符串等。key是一个用于排序的函数,它接受一个元素并返回一个用于排序的键。reverse参数用于指定是否按照降序排序,默认为False,即按照升序排序。
下面是一些例子来说明如何使用sorted()函数:
1. 对列表进行排序:
numbers = [3, 1, 4, 2, 5] sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出: [1, 2, 3, 4, 5]
2. 对元组进行排序:
names = ('Alice', 'Bob', 'Charlie')
sorted_names = sorted(names)
print(sorted_names) # 输出: ['Alice', 'Bob', 'Charlie']
3. 对字符串进行排序:
string = 'python' sorted_string = sorted(string) print(sorted_string) # 输出: ['h', 'n', 'o', 'p', 't', 'y']
4. 根据关键字进行排序:
students = [('Alice', 20), ('Bob', 18), ('Charlie', 22)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students) # 输出: [('Bob', 18), ('Alice', 20), ('Charlie', 22)]
在这个例子中,使用了lambda函数作为key参数,按照学生的年龄进行排序。
5. 按照降序排序:
numbers = [3, 1, 4, 2, 5] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers) # 输出: [5, 4, 3, 2, 1]
除了这些基本用法,sorted()函数还可以用于更复杂的场景。例如,可以通过组合多个排序键,来进行多级排序;还可以使用自定义的比较函数来实现特定的排序规则。
需要注意的是,sorted()函数返回一个新的已排序的列表,而不会修改原始的可迭代对象。
综上所述,sorted()函数是Python中用于对可迭代对象进行排序的一个非常有用的函数,通过指定待排序对象、关键字参数和比较函数等参数,我们可以灵活地进行排序操作。
