python——排序
内置函数sorted与itemgetter
- sorted(iter, key, reverse)
- itemgetter 获取对象的某一些维度作为排序依据
from operator import itemgetter
# 列表排序
l1 = [92, 91, 97, 97, 61, 66, 99, 49, 100, 35, 31, 100]
print(l1)
print(sorted(l1))
l1.sort()
print(l1)
# 元组排序
print('-' * 50)
l2 = [('dave', 'C', 15), ('jane', 'A', 20), ('john', 'B', 10)]
print(l2)
print(sorted(l2, key=lambda x: x[0].lower(), reverse=True))
l2.sort(key=lambda x: x[2])
print(l2)
# 字典排序, 使用itemgetter
print('-' * 50)
mydict = {
'Li': ['M', 7],
'Zhang': ['E', 2],
'Wang': ['P', 3],
'Du': ['C', 2],
'Ma': ['C', 9],
'Zhe': ['H', 7]
}
print(mydict)
print(sorted(mydict.items(), key=itemgetter(0)))
# 字典排序, 使用itemgetter多维度排序
print('-' * 50)
game_result = [
{"name": "Bob", "wins": 10, "losses": 3, "rating": 75.00},
{"name": "David", "wins": 3, "losses": 5, "rating": 57.00},
{"name": "Carol", "wins": 4, "losses": 5, "rating": 57.00},
{"name": "Patty", "wins": 9, "losses": 3, "rating": 71.48}
]
print(sorted(game_result,key=itemgetter('rating','wins')))
- 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', 'C', 20),
Student('dave', 'B', 10),
]
print(sorted(student_objects, key= attrgetter('grade')))