Advanced usage of python max and min functions

First, let's take a look at the normal usage of normal max and min:

students={'zs':18,'ls':21,'wu':19}
print(max(students.values()))  #21

Such a comparison does take out the largest age, but it's completely unknown to whom this corresponds. We can use the following methods to process the data to achieve our requirements.

students = { ' zs ' : 18, ' ls ' : 21, ' wu ' : 19 }
stu=zip(students.values(),students.keys())
print(max(stu))  #(21, 'ls')  

#That is to say, before we use max or min to sort, we can process the data first, which can achieve a more ideal effect

Let's take a look at the prototype of the max function. max(iterable, key, default) . The essence of the max function is to traverse the incoming parameters, and then return one of its elements. As for the key, a function is passed in, and its role is to decide what to compare the size by.

students=[
        {'name':'zs','age':18},
        {'name':'ls','age':21},
        {'name':'ww','age':19}
    ]
    print(max(students,key=lambda dict:dict['age']))    #{'name': 'ls', 'age': 21}

  First, let's look at the return value of the above code. No matter how the key is operated, the return value must be an element of students, which is a dictionary. Then the following key function is to process the traversed elements and decide which part to compare.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325164587&siteId=291194637