def func(p):
   return p.totalScore     
Copy the code

Now Max becomes:

max(players, key=func)
Copy the code

But because DEF statements are compound statements, they cannot be used where expressions are needed, which is why lambda is sometimes used.

Note that lambda is the same as if you were in a def return statement. Therefore, statements cannot be used in lambda, only expressions are allowed.

What is Max?

Max (a, b, c,… [, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

Therefore, it returns only the largest object.

set of rules

To modify an object before a comparison or to compare based on a specific property/index, you must use key parameters.

Embodiment 1:

As a simple example, suppose you have a list of numbers in the form of a string, but you want to compare the integer values of the items.

Here Max compares items using their raw values (strings are dictionary comparisons, so you’ll get ‘2’ as output) :

To compare items by their integer values, use the key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  #compare `int` version of each item
'111'
Copy the code

Example 2: Apply Max to list lists.

>>> lis = [(1,'a'),(3,'c'), (4,'e'), (-1,'z')]
Copy the code

By default, Max will compare items by the first index and the second index if the first index is the same. In my example, all items have a unique first index, so you get this answer:

>>> max(lis)
(4, 'e')
Copy the code

But what if you want to compare each item by the value of index 1? Simple, use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')
Copy the code

Compare items in iterable that contain objects of different types:

List of mixed projects:

>>> lis = ['1','100','111','2', 2, 2.57]
Copy the code

In Python 2 it is possible to compare items of two different types:

But in Python 3 you can’t do that any more:

> > > the lis = [' 1 ', '100', '111', '2', 2, 2.57] > > > Max (lis) Traceback (the most recent call last) : the File "& lt; ipython-input-2-0ce0a02693e4>" , line 1, in < module> max(lis) TypeError: unorderable types: int() > str()Copy the code

But this works because we compare the integer versions of each object:

Type on the blackboard, so if you want to return the dictionary item with the largest value, just do the following:

>>> prices = { ... 'A':123, ... 'B' : 450.1,... 'C':12, ... 'E':444, ... } > > > Max (prices. The items (), key = lambda x: x [1]), 'B', 450.1) > > >Copy the code
  • Reference: Python Max functions use ‘keys’ and lambda expressions