Python中的sorted函数应用场景详解
发布时间:2023-06-24 14:14:42
Python中的sorted函数是一个常用的排序函数,它可以对Python内置类型的列表、元组、字符串等进行排序,也可以对自定义对象进行排序。
以下是sorted函数的应用场景详解:
1. 对列表进行排序
sorted函数可以对列表进行升序或降序排序,示例如下:
num_list = [7, 2, 5, 3, 1, 4, 6] sorted(num_list) # [1, 2, 3, 4, 5, 6, 7] sorted(num_list, reverse=True) # [7, 6, 5, 4, 3, 2, 1]
2. 对元组进行排序
sorted函数同样可以对元组进行排序,示例如下:
num_tuple = (7, 2, 5, 3, 1, 4, 6) sorted(num_tuple) # [1, 2, 3, 4, 5, 6, 7] sorted(num_tuple, reverse=True) # [7, 6, 5, 4, 3, 2, 1]
3. 对字符串进行排序
sorted函数可以对字符串进行排序,它会将字符串转换成单个字符列表进行排序,示例如下:
string = 'python is great' sorted(string) # [' ', ' ', 'a', 'e', 'g', 'h', 'i', 'n', 'o', 'p', 'r', 's', 't', 't', 'y']
4. 对字典进行排序
sorted函数还可以对字典的键进行排序,例如:
score_dict = {'Tom': 80, 'Jerry': 90, 'Lucy': 75}
sorted(score_dict) # ['Jerry', 'Lucy', 'Tom'], 按字典键升序排序
如果要对字典的值进行排序,可以结合lambda表达式和items方法,示例如下:
sorted(score_dict.items(), key=lambda x: x[1], reverse=True) # [('Jerry', 90), ('Tom', 80), ('Lucy', 75)], 按字典的值降序排序
5. 对自定义对象进行排序
如果要对自定义对象进行排序,可以定义一个__lt__方法,用于比较对象的大小,示例如下:
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __lt__(self, other):
return self.score < other.score
stu1 = Student('Tom', 80)
stu2 = Student('Jerry', 90)
stu3 = Student('Lucy', 75)
stu_list = [stu1, stu2, stu3]
sorted(stu_list, key=lambda stu: stu.score) # [<__main__.Student object at 0x000001>, <__main__.Student object at 0x000002>, <__main__.Student object at 0x000003>]
以上就是sorted函数的应用场景详解。sorted函数可以轻松排序各种Python内置类型,也可以对自定义对象进行排序,是Python开发中的常用函数之一。
