Python中的sorted函数的用法与实例
发布时间:2023-05-30 07:12:59
Python中的sorted()函数是一个内置函数,用来对一个序列进行排序。sorted()函数返回一个排好序的序列,保留原始序列不变。
sorted()函数的语法如下:
sorted(iterable[, key][, reverse])
其中,iterable是需要排序的序列,key是一个可选参数,用来指定一个函数来作为排序依据,reverse也是一个可选参数,用来控制是否降序排序。
下面是sorted()函数的一些常见用法与实例:
1. 对列表进行排序
num_list = [3, 7, 1, 9, 2, 5] sorted_list = sorted(num_list) print(sorted_list) # [1, 2, 3, 5, 7, 9]
2. 对字符串进行排序
string = "hello world" sorted_string = sorted(string) print(sorted_string) # [' ', 'd', 'e', 'h', 'l', 'l', 'o', 'o', 'r', 'w']
3. 对字典按值排序
price = {'apple': 0.5, 'orange': 0.3, 'banana': 0.2, 'peach': 0.6}
sorted_price = sorted(price.items(), key=lambda x: x[1])
print(sorted_price) # [('banana', 0.2), ('orange', 0.3), ('apple', 0.5), ('peach', 0.6)]
4. 对字典按键排序
price = {'apple': 0.5, 'orange': 0.3, 'banana': 0.2, 'peach': 0.6}
sorted_price = sorted(price.items(), key=lambda x: x[0])
print(sorted_price) # [('apple', 0.5), ('banana', 0.2), ('orange', 0.3), ('peach', 0.6)]
5. 对嵌套列表按指定元素排序
people = [['Tom', 23, 'M'], ['Mary', 18, 'F'], ['John', 22, 'M'], ['Lily', 20, 'F']] sorted_people = sorted(people, key=lambda x: x[1]) print(sorted_people) # [['Mary', 18, 'F'], ['Lily', 20, 'F'], ['John', 22, 'M'], ['Tom', 23, 'M']]
总之,sorted()函数是Python中一个十分实用的排序函数,能够帮助我们快速对一个序列进行排序,并灵活地指定排序的方式。
