Python中的sorted()函数:排序列表
Python中的sorted()函数是一个内置函数,用于对列表、元组等可迭代对象进行排序。sorted()函数可以对数字、字符串以及其他可比较的对象进行排序,并返回一个新的有序列表。本文将介绍sorted()函数的基本用法、参数和应用。
1.基本用法
sorted()函数基本语法为:
sorted(iterable, key=None, reverse=False)
其中:
- iterable:需要排序的可迭代对象,可以是列表、元组、集合等。
- key:指定排序的规则,可接受一个函数或lambda表达式作为参数。如果不指定,则默认按照元素的大小进行排序。
- reverse:布尔值,指定是否降序排序。默认为False,即升序排序。
例如,对一个列表进行排序:
nums = [10, 8, 15, 20, 3]
sorted_nums = sorted(nums)
print(sorted_nums)
输出结果为:
[3, 8, 10, 15, 20]
2.参数使用
2.1 按照字符串长度排序
对于一个字符串列表,可以根据字符串长度进行排序。例如:
words = ['apple', 'banana', 'pear', 'orange', 'grape']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)
输出结果为:
['pear', 'apple', 'grape', 'banana', 'orange']
2.2 按照字典的值排序
对于一个字典,可以使用sorted()函数对其值进行排序。例如:
d = {'a': 2, 'b': 1, 'c': 3}
sorted_d = sorted(d.items(), key=lambda x: x[1])
print(sorted_d)
输出结果为:
[('b', 1), ('a', 2), ('c', 3)]
2.3 按照多个字段排序
对于一个嵌套的字典列表,可以使用sorted()函数按照多个字段进行排序。例如:
users = [{'name': 'Amy', 'age': 25, 'gender': 'female'},
{'name': 'Bob', 'age': 30, 'gender': 'male'},
{'name': 'Cathy', 'age': 20, 'gender': 'female'},
{'name': 'David', 'age': 25, 'gender': 'male'}]
sorted_users = sorted(users, key=lambda x: (x['age'], x['name']))
print(sorted_users)
输出结果为:
[{'name': 'Cathy', 'age': 20, 'gender': 'female'},
{'name': 'Amy', 'age': 25, 'gender': 'female'},
{'name': 'David', 'age': 25, 'gender': 'male'},
{'name': 'Bob', 'age': 30, 'gender': 'male'}]
3.应用场景
3.1 排序学生成绩
sorted()函数可以方便地对学生成绩进行排序。例如,有如下学生成绩表:
students = [
{'name': 'Tom', 'score': 85},
{'name': 'Mary', 'score': 92},
{'name': 'John', 'score': 88},
{'name': 'Bob', 'score': 75},
{'name': 'Alice', 'score': 80}
]
可以使用sorted()函数对学生成绩进行排序:
sorted_students = sorted(students, key=lambda x: x['score'], reverse=True)
for student in sorted_students:
print(student['name'], student['score'])
输出结果为:
Mary 92
John 88
Tom 85
Alice 80
Bob 75
3.2 数据库查询结果排序
在数据库查询结果中,如果需要按照某个字段进行排序,可以使用sorted()函数。例如,假设要按照年龄从小到大的顺序对姓名列表进行排序:
names = [('Tom', 25), ('Mary', 18), ('John', 30), ('Bob', 20)]
sorted_names = sorted(names, key=lambda x: x[1])
for name in sorted_names:
print(name[0], name[1])
输出结果为:
Mary 18
Bob 20
Tom 25
John 30
4.总结
sorted()函数是Python中一个非常常用的排序函数,可以用于对数字、字符串、列表、元组等可迭代对象进行排序。sorted()函数有多种参数,可以根据需求进行灵活使用。在实际开发中,sorted()函数可以处理大部分的排序需求,大大提高了程序的开发效率。
