欢迎访问宙启技术站
智能推送

“Python中的sorted函数及其用法”

发布时间:2023-05-30 03:44:27

在Python中,sorted()函数是非常常见的内置函数,可以对列表、元组、字符串等进行排序。sorted()函数排序的方式有多种,包括从小到大(升序)、从大到小(降序)、根据特定的键(key)排序等。

函数语法:

sorted(iterable, key=None, reverse=False)

其中:

- iterable:用于排序的可迭代对象,例如列表、元组、字符串等。

- key:用来指定排序的比较函数,即根据这个函数的返回值来排序。可选参数,默认值为None,表示按照元素自身的大小进行比较。

- reverse:表示排序顺序,可选参数,默认为False,表示从小到大排序,如果为True,则表示从大到小排序。

下面将具体介绍sorted()函数的用法:

1. 列表排序

对于一个列表来说,使用sorted()函数进行顺序排列是非常方便的。例如:

lst = [2, 5, 7, 9, 1, 3, 6, 8, 4]
new_lst1 = sorted(lst)      # 默认从小到大排序
new_lst2 = sorted(lst, reverse=True)     # 从大到小排序
print(new_lst1)         # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(new_lst2)         # [9, 8, 7, 6, 5, 4, 3, 2, 1]

2. 元组排序

对于一个元组来说,同样可以使用sorted()函数进行排序。不过需要注意的是,排序后返回的是一个列表,而不是元组。例如:

tup = (2, 5, 7, 9, 1, 3, 6, 8, 4)
new_tup1 = tuple(sorted(tup))        # 将排序后的列表转换为元组
new_tup2 = tuple(sorted(tup, reverse=True))
print(new_tup1)         # (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(new_tup2)         # (9, 8, 7, 6, 5, 4, 3, 2, 1)

3. 字符串排序

对于字符串来说,可以使用sorted()函数对其进行排序,排序后的结果也是一个字符串列表。例如:

str = "python is a great language"
new_str1 = "".join(sorted(str))       # 将排序后的列表转换为字符串
new_str2 = "".join(sorted(str, reverse=True))
print(new_str1)         # '       aagdeeghilnnoprstty'
print(new_str2)         # 'ytsroprnliihgeeda ga si nohtyp'

4. 对字典按键排序

如果想要对一个字典按照键(key)进行排序,可以通过sorted()函数结合键来排序。例如:

dct = {"apple": 10, "pear": 12, "banana": 8, "orange": 15}
new_dct = dict(sorted(dct.items()))       # 将排序后的元组转换为字典
print(new_dct)         # {'apple': 10, 'banana': 8, 'orange': 15, 'pear': 12}

5. 根据特定函数排序

有时候,我们需要对一个列表按照特定的规则进行排序,可以通过定义一个函数,并将这个函数作为sorted()函数的key参数。例如:

lst = ["apple", "pear", "banana", "orange"]
new_lst = sorted(lst, key=lambda x: len(x))       # 将长度作为排序参数
print(new_lst)         # ['pear', 'apple', 'orange', 'banana']

以上就是sorted()函数的基本用法了,希望能够对大家有所帮助。