[Python] How to Sort a Group of Tuples Using the Sorted() Function

[question]
Suppose we use a set of tuples to represent students’ names and grades:

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

With sorted() sorted the above lists by name:

# Sort by name

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 

def by_name(t):
    return t[0].lower()

L2 = sorted(L, key=by_name)
print(L2)

Operation results:

[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]

【 description 】
About indexes:
L = [(‘ Bob ‘, 75), (‘ Adam ‘, 92), (‘ Bart, 66), (88) ‘Lisa’]
L [0] is (75), ‘Bob’
L[0][0] is “Bob”
and so on
Here, we need to understand:
The key to sorting () is implementing a mapping function. The function specified by the key will act on each element of the list and sort by the result returned by the key function. The final result: Returns the corresponding elements of the original list in the order of the key function
So the actual argument to the by_name function is each element in L, the tuple primitive in the list.

so, sort the contents of the list by name:
The by_name function does all the lowercase handling of the first element of the tuple, the name string t[0], with the lower() function, and returns the result. The by_name function ACTS one by one on each primitive in L, and sorts the original elements in L according to the order of function results.
In the same way, it can be realized and ranked from high to low in terms of performance:

# In descending order of performance

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 

def by_score(t):
    return t[1]

L2 = sorted(L, key=by_score,reverse=True)
print(L2)

Operation results:

[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]

Read More: