对list进行排序
- 利用list的成员函数sort()排序
- 利用内置函数(built-in function) sorted()进行排序
两者的区别
- sort() 对list本身进行排序,改变list的值。sort()只能对list排序。
- sorted() 产生一个新的list,不改变list的值。sorted()可以对iterable对象排序
举例:
l = [12, 34, 21, 45, 12, 7, 2]
l.sort()
print(l)
l2 = [12, 34, 21, 45, 12, 7, 2]
l3 = sorted(l2)
print(l2)
print(l3)
结果为:
[2, 7, 12, 12, 21, 34, 45]
[12, 34, 21, 45, 12, 7, 2]
[2, 7, 12, 12, 21, 34, 45]
sorted()函数详细讲解
sorted(iterable, key=None, reverse=False)
- iterable为可迭代类型
- key 确定要调用的函数以用于对list的每个元素进行比较。通常使用lambda表达式
- reverse默认值为False,此时sorted()按从小到大的顺序排序。当reverse=True时,按照从大到小的顺序排序。
- key,reverse为可选参数。
举个例子
举例1:按照tuple中第二个值的大小对List进行排序
L = [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
print(sorted(L, key=lambda x: x[1], reverse=True))
print(sorted(L, key=lambda x: x[1]))
结果:
[('d', 4), ('c', 3), ('b', 2), ('a', 1)]
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
举例2:按照dict的长度对List进行排序
L = [{1: 2, 3: 4}, {1: 4}, {4: 5, 8: 9, 9: 2}]
print(sorted(L, key=lambda x: len(x)))
结果:
[{1: 4}, {1: 2, 3: 4}, {8: 9, 9: 2, 4: 5}]
使用operator模块的函数
- itemgetter()可以简单的理解为itemgetter(x)就是获取第几个元素的值。
- attrgetter()可以简单的理解为attrgetter(attrname)就是获取对象某个属性的值
举例:使用itemgetter()
from operator import itemgetter
L= [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
print(sorted(L, key = itemgetter(1)))
结果:
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
举例:使用attrgetter()
from operator import attrgetter
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
print(sorted(student_objects, key=lambda stu: stu.age))
print(sorted(student_objects, key=attrgetter('age')))
结果:
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
使用operator模块的函数进行多级排序
举例:使用itemgetter()实现多级排序
from operator import itemgetter
L= [('b', 2), ('a', 2), ('c', 3), ('d', 4)]
print(sorted(L, key = itemgetter(1, 0)))
结果:
[('a', 2), ('b', 2), ('c', 3), ('d', 4)]
举例:使用attrgetter()实现多级排序
from operator import attrgetter
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
print(sorted(student_objects, key=attrgetter('name', 'age')))
结果:
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]