Python函数如何实现数据排序
发布时间:2023-05-28 13:27:16
在Python中,实现数据排序可以使用内置函数sorted()或sort(),也可以通过自定义函数来实现。
1. 使用内置函数sorted()
sorted()函数用于对列表、元组、字典等可迭代对象进行排序,它返回一个新列表,原来的列表不变。
示例代码:
a = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9] b = sorted(a) print(b)
输出结果:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 8, 9, 9, 9]
sort()与sorted()的区别:
sort()函数用于对列表进行排序,它直接修改原来的列表,不返回值。示例代码:
a = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9] a.sort() print(a)
输出结果:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 8, 9, 9, 9]
2. 自定义排序函数
如果需要对复杂数据类型进行排序,例如列表中包含字典,可以使用自定义排序函数。
示例代码:
def sort_by_age(person):
return person['age']
people = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 20},
{'name': 'Charlie', 'age': 30},
{'name': 'David', 'age': 26},
{'name': 'Eve', 'age': 22}
]
sorted_people = sorted(people, key=sort_by_age)
for person in sorted_people:
print(person['name'], person['age'])
输出结果:
Bob 20 Eve 22 Alice 25 David 26 Charlie 30
在自定义排序函数中,使用key参数指定排序关键字。key参数接受一个函数作为参数,该函数接受一个元素作为参数,并返回用于排序的关键字。在上面的示例中,sort_by_age()函数用于按照字典中的'age'关键字进行排序。
