Python的内置函数sorted():如何进行排序操作?
发布时间:2023-09-11 20:48:59
Python的内置函数sorted()是用来对可迭代对象进行排序操作的,它可以接受一个可迭代对象作为参数,返回一个新的列表,其中包含了排序后的元素。
sorted()函数可以对多种类型的可迭代对象进行排序,包括列表、元组、字符串等。它还可以接受一个关键字参数key,用来指定排序时使用的比较函数。
默认情况下,sorted()函数会使用元素的自然顺序进行排序。对于数值类型的元素,会按照升序进行排序;对于字符串类型的元素,会按照字母顺序进行排序。
下面是一些使用sorted()函数进行排序的例子:
1. 对列表进行排序:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
2. 对字符串进行排序:
chars = "python" sorted_chars = sorted(chars) print(sorted_chars) # 输出: ['h', 'n', 'o', 'p', 't', 'y']
3. 对元组进行排序:
points = [(1, 2), (3, 1), (5, 3), (4, 6), (2, 4)] sorted_points = sorted(points) print(sorted_points) # 输出: [(1, 2), (2, 4), (3, 1), (4, 6), (5, 3)]
关键字参数key可以用来指定一个比较函数,该函数接受一个元素作为参数,返回一个用于排序的关键字。例如,可以使用key参数来按照元组中的第二个元素进行排序:
points = [(1, 2), (3, 1), (5, 3), (4, 6), (2, 4)] sorted_points = sorted(points, key=lambda x: x[1]) print(sorted_points) # 输出: [(3, 1), (1, 2), (5, 3), (2, 4), (4, 6)]
可以使用reverse参数来指定排序的顺序,默认为False(升序),设置为True时可以得到降序排序的结果:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers) # 输出: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
在某些情况下,sorted()函数还可以接受一个可调用的参数cmp用来进行比较,但在Python 3中已经被废弃,不建议使用。
总而言之,sorted()函数是Python内置的强大工具,可以方便地对可迭代对象进行排序操作,同时也提供了一些参数来进行更复杂的排序。
