Perform some functional operations on the dictionary list and class object list, and use the key keyword

Operate on the dictionary list

For example, we want to sort according to a key value of the dictionary. The
general method should be done using some sorting methods, such as bubble sorting, which is to compare one by one and exchange positions when the conditions are met.

persons = [
    {
    
    'name':'张三','age':18,'score':80},
    {
    
    'name':'李四','age':17,'score':70},
    {
    
    'name':'王五','age':18,'score':89},
    {
    
    'name':'马六','age':20,'score':100},
    {
    
    'name':'赵七','age':19,'score':60},
]
# 这里我就没有做过多的优化了,大家可以去尝试优化优化一下,也就是减小比较次数
for i in range(len(persons)-1):
    for j in range(len(persons)-1-i):
        if persons[j]['age']>persons[j+1]['age']:
            persons[j],persons[j+1] = persons[j+1],persons[j]
print(persons)
# [{'name': '李四', 'age': 17, 'score': 70}, {'name': '张三', 'age': 18, 'score': 80}, {'name': '王五', 'age': 18, 'score': 89}, {'name': '赵七', 'age': 19, 'score': 60}, {'name': '马六', 'age': 20, 'score': 100}]

Here we can think about it. They are all lists. Can we use the sort() method?
The answer is of course yes, note that the use of anonymous functions is involved here

# 都是操作的上面那个列表这里我就不再写了
# 注意些操作完一个就注释一个
# 这里我们需要用到key关键字
# 根据age对它们进行排序
# 这是列表的sort方法,会改变原来列表的数据,而不是返回一个新列表
# persons.sort(key=lambda p:p['age'])
# print(persons)
# [{'name': '李四', 'age': 17, 'score': 70}, {'name': '张三', 'age': 18, 'score': 80}, {'name': '王五', 'age': 18, 'score': 89}, {'name': '赵七', 'age': 19, 'score': 60}, {'name': '马六', 'age': 20, 'score': 100}]

# sorted函数则是返回一个新的列表,这里我就直接打印了
# 这是根据score进行排序的
# print(sorted(persons,key=lambda a:a['score']))
# [{'name': '赵七', 'age': 19, 'score': 60}, {'name': '李四', 'age': 17, 'score': 70}, {'name': '张三', 'age': 18, 'score': 80}, {'name': '王五', 'age': 18, 'score': 89}, {'name': '马六', 'age': 20, 'score': 100}]

# 根据多个字段进行排序,哪个写在前就以哪个为主
# print(sorted(persons,key=lambda s:(s['age'],s['score'])))
# [{'name': '李四', 'age': 17, 'score': 70}, {'name': '张三', 'age': 18, 'score': 80}, {'name': '王五', 'age': 18, 'score': 89}, {'name': '赵七', 'age': 19, 'score': 60}, {'name': '马六', 'age': 20, 'score': 100}]
# 这里没发生什么改变是因为age重复的少,大家在做测试的时候可以多给一点数据,这样就可以更为清楚的观察

Understand : In fact, the key keyword can also be followed by the itemgetter() function, which has the same effect as an anonymous function, but the itemgetter() function runs more efficiently. Here you need to import a module

from operator import itemgetter

# print(sorted(persons,key=itemgetter('age')))
# [{'name': '李四', 'age': 17, 'score': 70}, {'name': '张三', 'age': 18, 'score': 80}, {'name': '王五', 'age': 18, 'score': 89}, {'name': '赵七', 'age': 19, 'score': 60}, {'name': '马六', 'age': 20, 'score': 100}]
# print(sorted(persons,key=itemgetter('age','score')))
# [{'name': '李四', 'age': 17, 'score': 70}, {'name': '张三', 'age': 18, 'score': 80}, {'name': '王五', 'age': 18, 'score': 89}, {'name': '赵七', 'age': 19, 'score': 60}, {'name': '马六', 'age': 20, 'score': 100}]

The max(), min() functions also support the above operations

from operator import itemgetter
fruits = [
    {
    
    'name':'梨','price':5},
    {
    
    'name':'苹果','price':4.5},
    {
    
    'name':'车厘子','price':20},
    {
    
    'name':'香蕉','price':6},
    {
    
    'name':'火龙果','price':10},
]
# 求价格最高的水果
# 生成器表达式和列表推导式就只能求出最高的价格
print(max(s['price'] for s in fruits))# 20

print(max(fruits,key= lambda s:s['price']))
# {'name': '车厘子', 'price': 20}

print(min(fruits,key=itemgetter('price')))
# {'name': '苹果', 'price': 4.5}

Operate on the list of class objects

The key keyword can also be used here, and the attrgetter() method in the operator module can also be used

from operator import attrgetter
class Person:
    def __init__(self,age):
        self.age = age
    def __repr__(self):# 打印类对象时格式
        return f'User({self.age})'
persons = [Person(10),Person(20),Person(15)]
# persons.sort(key=lambda p:p.age)
# print(persons)# [Person(10), Person(15), Person(20)]

print(sorted(persons,key=attrgetter('age')))# [Person(10), Person(15), Person(20)]

print(max(persons,key=attrgetter('age')))# Person(20)
print(min(persons,key=attrgetter('age')))# Person(10)

I hope this content is helpful to everyone
Remember to like QAQ

Guess you like

Origin blog.csdn.net/hmh4640219/article/details/112785497