Python函数:sorted()函数的使用方法和案例
发布时间:2023-06-12 06:55:16
sorted()函数是Python内置的一个高阶函数,用于对可迭代对象进行排序操作。它可以对列表、元组、集合、字符串等数据类型进行排序,支持按照不同的排序规则进行排序,不会对原可迭代对象进行修改,会返回一个新的已排序的对象。
sorted(iterable, key=None, reverse=False)
其中,iterable为要排序的可迭代对象,key和reverse为可选参数,key用于指定一个函数作为排序规则,reverse用于控制是否进行倒序排序。
下面通过几个案例来介绍sorted()函数的使用方法。
案例1:对列表进行排序
a = [5, 3, 1, 4, 2] b = sorted(a) # 升序排序 c = sorted(a, reverse=True) # 降序排序 print(b) # [1, 2, 3, 4, 5] print(c) # [5, 4, 3, 2, 1]
案例2:对元组进行排序
a = (5, 3, 1, 4, 2) b = sorted(a) # 升序排序 c = sorted(a, reverse=True) # 降序排序 print(b) # [1, 2, 3, 4, 5] print(c) # [5, 4, 3, 2, 1]
案例3:对字符串进行排序
a = '53142' b = sorted(a) # 升序排序 c = sorted(a, reverse=True) # 降序排序 print(b) # ['1', '2', '3', '4', '5'] print(c) # ['5', '4', '3', '2', '1']
案例4:按照指定排序规则进行排序
a = ['abc', 'acd', 'bce', 'defg', 'abcde'] b = sorted(a, key=len) # 按照字符串长度升序排序 c = sorted(a, key=lambda x: x[-1]) # 按照字符串最后一个字符升序排序 print(b) # ['abc', 'acd', 'bce', 'defg', 'abcde'] -> ['abc', 'acd', 'bce', 'defg', 'abcde'] print(c) # ['abc', 'defg', 'acd', 'abcde', 'bce'] -> ['abc', 'bce', 'acd', 'abcde', 'defg']
从案例中可以看出,sorted()函数具有很强的灵活性,可以满足我们对不同数据类型和排序规则的需求。当需要排序时,我们应该优先考虑使用sorted()函数,而不是手动实现排序算法。
