python max函数使用'key'和lambda表达式。

时间:2020-11-30 18:03:41

I come from OOP background and trying to learn python. I am using the max function which uses a lambda expression to return the instance of type Player having maximum totalScore among the list players.

我来自OOP背景,并试图学习python。我使用的是max函数,它使用lambda表达式返回类型播放器的实例,在列表播放器中有最大的totalScore。

def winner():
    w = max(players, key=lambda p: p.totalScore)

The function correctly returns instance of type Player having maximum totalScore. I am confused about the following three things:

该函数正确地返回具有最大totalScore的类型播放器的实例。我对以下三件事感到困惑:

  1. How does the max function work? What are the arguments it is taking? I looked at the documentation but failed to understand.
  2. max函数是如何工作的?它的论据是什么?我查看了文档,但没能理解。
  3. What is use of the keyword key in max function? I know it is also used in context of sort function
  4. 在max函数中关键字键的使用是什么?我知道它也被用于排序函数的上下文。
  5. Meaning of the lambda expression? How to read them? How do they work?
  6. lambda表达式的含义?如何阅读?他们如何工作?

These are all very noobish conceptual questions but will help me understand the language. It would help if you could give examples to explain. Thanks

这些都是非常重要的概念性问题,但会帮助我理解这门语言。如果你能举出例子来解释,那将会有帮助。谢谢

6 个解决方案

#1


159  

lambda is an anonymous function, it is equivalent to:

是一个匿名函数,它等于:

def func(p):
   return p.totalScore     

Now max becomes:

现在最多就变成:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

但是,当def语句是复合语句时,它们不能在需要表达式的地方使用,这就是为什么有时使用lambda的原因。

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.

注意,lambda与您在def的返回语句中所添加的内容相当。因此,您不能在lambda中使用语句,只允许表达式。


What does max do?

马克斯是干什么的?

max(a, b, c, ...[, key=func]) -> value

max(a,b,c,……(关键= func])- >价值

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

使用一个可迭代的参数,返回其最大的项。使用两个或多个参数,返回最大的参数。

So, it simply returns the object that is largest.

它只返回最大的对象。


How `key` works?

By default in Python 2 key compares items based on a set of rules based on the type of the objects(for example a string is always greater than an integer).

在Python 2中,默认情况下,根据对象的类型(例如字符串总是大于整数)来比较基于规则集的项。

To modify the object before comparison or to compare based on a particular attribute/index you've to use the key argument.

要在比较之前修改对象或基于特定的属性/索引进行比较,您必须使用关键参数。

Example 1:

示例1:

A simple example, suppose you've a list of numbers in string form, but you want to compare those items by their integer value.

一个简单的例子,假设您有一个字符串形式的数字列表,但是您想要用它们的整数值来比较这些项。

>>> lis = ['1','100','111','2']

Here max compares the items using their original values(strings are compared lexicographically so you'd get '2' as output) :

这里max用它们的原始值来比较这些项(字符串比较词法,所以你可以得到“2”作为输出):

>>> max(lis)
'2'

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

用一个简单的lambda值来比较它们的整数值使用键值:

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

Example 2: Applying max to a list of lists.

例2:将max应用于列表列表。

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

By default max will will compare the items by the first index, if the first index is same then it'd compare the second index. As in my example all items have unique first index so, you'd get this as the answer:

默认情况下,max将会比较第一个索引中的项,如果第一个索引是相同的,那么它会比较第二个索引。在我的例子中,所有项目都有唯一的第一个索引,所以你会得到这个答案:

>>> max(lis)
(4, 'e')

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

但是,如果你想要用索引1中的值来比较每一项呢?简单,用λ:

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

Comparing items in an iterable that contains objects of different type:

比较包含不同类型对象的iterable中的项:

List with mixed items:

与混合物品列表:

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

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

在Python 2中,可以比较两种不同类型的项目:

>>> max(lis) # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) #compare integer version of each item
'111'

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

但是在Python 3中,你不能再这样做了:

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

But this works, as we are comparing integer version of each object:

但这是可行的,因为我们比较了每个对象的整数版本:

>>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)`
'111'

#2


8  

Strongly simplified version of max:

极大简化版的max:

def max(items, key=lambda x: x):
    current = item[0]
    for item in items:
        if key(item) > key(current):
            current = item
    return current

Regarding lambda:

关于λ:

>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5

>>> times_two = lambda x: 2*x
>>> times_two(2)
4

#3


8  

How does the max function work?

max函数是如何工作的?

It looks for the "largest" item in an iterable. I'll assume that you can look up what that is, but if not, it's something you can loop over, i.e. a list or string.

它在迭代中查找“最大”项。我假设您可以查找它是什么,但如果不是,它是您可以遍历的东西,即列表或字符串。

What is use of the keyword key in max function? I know it is also used in context of sort function

在max函数中关键字键的使用是什么?我知道它也被用于排序函数的上下文。

Key is a lambda function that will tell max which objects in the iterable are larger than others. Say if you were sorting some object that you created yourself, and not something obvious, like integers.

Key是一个lambda函数,它会告诉max在iterable中哪个对象比其他对象更大。如果你在排序你自己创建的对象,而不是一些明显的,比如整数。

Meaning of the lambda expression? How to read them? How do they work?

lambda表达式的含义?如何阅读?他们如何工作?

That's sort of a larger question. In simple terms, a lambda is a function you can pass around, and have other pieces of code use it. Take this for example:

这是一个更大的问题。简单地说,lambda是一个您可以传递的函数,并且有其他代码使用它。以这个为例:

def sum(a, b, f):
    return (f(a) + f(b))

This takes two objects, a and b, and a function f. It calls f() on each object, then adds them together. So look at this call:

这需要两个对象,a和b,以及一个函数f,它在每个对象上调用f(),然后将它们加在一起。所以看这个电话:

>>> sum(2, 2, lambda a:  a * 2)
8

sum() takes 2, and calls the lambda expression on it. So f(a) becomes 2 * 2, which becomes 4. It then does this for b, and adds the two together.

sum()取2,并调用它上的lambda表达式。所以f(a)变成2 * 2,变成4。然后对b做这个,把这两个相加。

In not so simple terms, lambdas come from lambda calculus, which is the idea of a function that returns a function; a very cool math concept for expressing computation. You can read about that here, and then actually understand it here.

在不太简单的条件下,lambdas来自于lambda演算,这是一个函数的概念,它返回一个函数;一个非常酷的数学概念用来表达计算。你可以在这里读到它,然后在这里真正理解它。

It's probably better to read about this a little more, as lambdas can be confusing, and it's not immediately obvious how useful they are. Check here.

也许最好再多读一点,因为lambdas可能会让人困惑,而且现在还不清楚它们是多么有用。检查在这里。

#4


5  

According to the documentation:

根据文档:

max(iterable[, key])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.

max(iterable[, key]) max(arg1, arg2, *args[, key])返回一个可迭代的或最大的两个或多个参数中的最大的项。

If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

如果提供了一个位置参数,则iterable必须是非空的iterable(如非空字符串、元组或列表)。iterable中最大的项返回。如果提供了两个或多个位置参数,则返回最大的位置参数。

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)).

可选的关键参数指定了一个单参数排序函数,如用于list.sort()的排序函数。如果提供了关键参数,则必须以关键字形式(例如,max(a,b,c,key=func))。

What this is saying is that in your case, you are providing a list, in this case players. Then the max function will iterate over all the items in the list and compare them to each other to get a "maximum".

这就是说,在你的案例中,你提供了一个列表,在这个例子中,玩家。然后,max函数将迭代列表中的所有项,并将它们进行比较,以获得“最大值”。

As you can imagine, with a complex object like a player determining its value for comparison is tricky, so you are given the key argument to determine how the max function will decide the value of each player. In this case, you are using a lambda function to say "for each p in players get p.totalscore and use that as his value for comparison".

正如您可以想象的那样,对于一个复杂的对象,比如一个玩家确定它的比较值是很复杂的,所以你会得到一个关键的参数来确定max函数是如何决定每个玩家的价值的。在这种情况下,你使用lambda函数来表示“对于每个p的参与者都得到p”。totalscore并将其用作比较的价值。

#5


4  

max function is used to get the maximum out of an iterable.

max函数被用来从迭代中得到最大的值。

The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.

迭代器可以是列表、元组、命令对象等,甚至可以是您提供的示例中的自定义对象。

max(iterable[, key=func]) -> value
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.

So, the key=func basically allows us to pass an optional argument key to the function on whose basis the the given iterator/arguments are sorted & the maximum is returned.

因此,key=func基本上允许我们传递一个可选的参数键到函数的基础上,给定的迭代器/参数被排序,并且返回最大值。

lambda is a python keyword that acts as a pseudo function. So, when you pass player object to it, it will return player.totalScore. Thus, the iterable passed over to function max will sort according to the key totalScore of the player objects given to it & will return the player who has maximum totalScore.

lambda是一个python关键字,充当pseudo函数。因此,当您将player对象传递给它时,它将返回player. totalscore。因此,迭代传递到函数max将根据给定的player对象的关键totalScore排序,并返回具有最大totalScore的播放器。

If no key argument is provided, the maximum is returned according to default Python orderings.

如果没有提供关键参数,则根据默认的Python命令返回最大值。

Examples -

的例子,

max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7

people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')

#6


0  

max is built in function which takes first argument an iterable (like list or tuple)

max是在函数中构建的,它以第一个参数为可迭代(如列表或元组)

keyword argument key has it's default value None but it accept function to evaluate, consider it as wrapper which evaluates iterable based on function

关键字参数键有它的默认值,但是它接受函数来评估,把它当作是基于函数的可迭代的包装器。

Consider this example dictionary:

考虑一下这个例子字典:

d = {'aim':99, 'aid': 45, 'axe': 59, 'big': 9, 'short': 995, 'sin':12, 'sword':1, 'friend':1000, 'artwork':23}

Ex:

例:

>>> max(d.keys())
'sword'

As you can see if you only pass the iterable without kwarg(a function to key) it is returning maximum value of key(alphabetically)

正如您所看到的,如果您只通过iterable,而没有kwarg(一个函数对键),那么它将返回键的最大值(按字母顺序)

Ex. Instead of finding max value of key alphabetically you might need to find max key by length of key:

不需要按字母顺序查找键的最大值,你可能需要按长度的键找到max键:

>>>max(d.keys(), key=lambda x: len(x))
'artwork'

in this example lambda function is returning length of key which will be iterated hence while evaluating values instead of considering alphabetically it will keep track of max length of key and returns key which has max length

在这个例子中,lambda函数是返回键的长度,它将被迭代,因此在评估值时,而不是按字母顺序考虑,它会跟踪键的最大长度,并返回最大长度的键。

Ex.

前女友。

>>> max(d.keys(), key=lambda x: d[x])
'friend'

in this example lambda function is returning value of corresponding dictionary key which has maximum value

在这个示例中,lambda函数返回对应的字典键值,该值具有最大值。

#1


159  

lambda is an anonymous function, it is equivalent to:

是一个匿名函数,它等于:

def func(p):
   return p.totalScore     

Now max becomes:

现在最多就变成:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

但是,当def语句是复合语句时,它们不能在需要表达式的地方使用,这就是为什么有时使用lambda的原因。

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.

注意,lambda与您在def的返回语句中所添加的内容相当。因此,您不能在lambda中使用语句,只允许表达式。


What does max do?

马克斯是干什么的?

max(a, b, c, ...[, key=func]) -> value

max(a,b,c,……(关键= func])- >价值

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

使用一个可迭代的参数,返回其最大的项。使用两个或多个参数,返回最大的参数。

So, it simply returns the object that is largest.

它只返回最大的对象。


How `key` works?

By default in Python 2 key compares items based on a set of rules based on the type of the objects(for example a string is always greater than an integer).

在Python 2中,默认情况下,根据对象的类型(例如字符串总是大于整数)来比较基于规则集的项。

To modify the object before comparison or to compare based on a particular attribute/index you've to use the key argument.

要在比较之前修改对象或基于特定的属性/索引进行比较,您必须使用关键参数。

Example 1:

示例1:

A simple example, suppose you've a list of numbers in string form, but you want to compare those items by their integer value.

一个简单的例子,假设您有一个字符串形式的数字列表,但是您想要用它们的整数值来比较这些项。

>>> lis = ['1','100','111','2']

Here max compares the items using their original values(strings are compared lexicographically so you'd get '2' as output) :

这里max用它们的原始值来比较这些项(字符串比较词法,所以你可以得到“2”作为输出):

>>> max(lis)
'2'

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

用一个简单的lambda值来比较它们的整数值使用键值:

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

Example 2: Applying max to a list of lists.

例2:将max应用于列表列表。

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

By default max will will compare the items by the first index, if the first index is same then it'd compare the second index. As in my example all items have unique first index so, you'd get this as the answer:

默认情况下,max将会比较第一个索引中的项,如果第一个索引是相同的,那么它会比较第二个索引。在我的例子中,所有项目都有唯一的第一个索引,所以你会得到这个答案:

>>> max(lis)
(4, 'e')

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

但是,如果你想要用索引1中的值来比较每一项呢?简单,用λ:

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

Comparing items in an iterable that contains objects of different type:

比较包含不同类型对象的iterable中的项:

List with mixed items:

与混合物品列表:

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

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

在Python 2中,可以比较两种不同类型的项目:

>>> max(lis) # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) #compare integer version of each item
'111'

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

但是在Python 3中,你不能再这样做了:

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

But this works, as we are comparing integer version of each object:

但这是可行的,因为我们比较了每个对象的整数版本:

>>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)`
'111'

#2


8  

Strongly simplified version of max:

极大简化版的max:

def max(items, key=lambda x: x):
    current = item[0]
    for item in items:
        if key(item) > key(current):
            current = item
    return current

Regarding lambda:

关于λ:

>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5

>>> times_two = lambda x: 2*x
>>> times_two(2)
4

#3


8  

How does the max function work?

max函数是如何工作的?

It looks for the "largest" item in an iterable. I'll assume that you can look up what that is, but if not, it's something you can loop over, i.e. a list or string.

它在迭代中查找“最大”项。我假设您可以查找它是什么,但如果不是,它是您可以遍历的东西,即列表或字符串。

What is use of the keyword key in max function? I know it is also used in context of sort function

在max函数中关键字键的使用是什么?我知道它也被用于排序函数的上下文。

Key is a lambda function that will tell max which objects in the iterable are larger than others. Say if you were sorting some object that you created yourself, and not something obvious, like integers.

Key是一个lambda函数,它会告诉max在iterable中哪个对象比其他对象更大。如果你在排序你自己创建的对象,而不是一些明显的,比如整数。

Meaning of the lambda expression? How to read them? How do they work?

lambda表达式的含义?如何阅读?他们如何工作?

That's sort of a larger question. In simple terms, a lambda is a function you can pass around, and have other pieces of code use it. Take this for example:

这是一个更大的问题。简单地说,lambda是一个您可以传递的函数,并且有其他代码使用它。以这个为例:

def sum(a, b, f):
    return (f(a) + f(b))

This takes two objects, a and b, and a function f. It calls f() on each object, then adds them together. So look at this call:

这需要两个对象,a和b,以及一个函数f,它在每个对象上调用f(),然后将它们加在一起。所以看这个电话:

>>> sum(2, 2, lambda a:  a * 2)
8

sum() takes 2, and calls the lambda expression on it. So f(a) becomes 2 * 2, which becomes 4. It then does this for b, and adds the two together.

sum()取2,并调用它上的lambda表达式。所以f(a)变成2 * 2,变成4。然后对b做这个,把这两个相加。

In not so simple terms, lambdas come from lambda calculus, which is the idea of a function that returns a function; a very cool math concept for expressing computation. You can read about that here, and then actually understand it here.

在不太简单的条件下,lambdas来自于lambda演算,这是一个函数的概念,它返回一个函数;一个非常酷的数学概念用来表达计算。你可以在这里读到它,然后在这里真正理解它。

It's probably better to read about this a little more, as lambdas can be confusing, and it's not immediately obvious how useful they are. Check here.

也许最好再多读一点,因为lambdas可能会让人困惑,而且现在还不清楚它们是多么有用。检查在这里。

#4


5  

According to the documentation:

根据文档:

max(iterable[, key])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.

max(iterable[, key]) max(arg1, arg2, *args[, key])返回一个可迭代的或最大的两个或多个参数中的最大的项。

If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

如果提供了一个位置参数,则iterable必须是非空的iterable(如非空字符串、元组或列表)。iterable中最大的项返回。如果提供了两个或多个位置参数,则返回最大的位置参数。

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)).

可选的关键参数指定了一个单参数排序函数,如用于list.sort()的排序函数。如果提供了关键参数,则必须以关键字形式(例如,max(a,b,c,key=func))。

What this is saying is that in your case, you are providing a list, in this case players. Then the max function will iterate over all the items in the list and compare them to each other to get a "maximum".

这就是说,在你的案例中,你提供了一个列表,在这个例子中,玩家。然后,max函数将迭代列表中的所有项,并将它们进行比较,以获得“最大值”。

As you can imagine, with a complex object like a player determining its value for comparison is tricky, so you are given the key argument to determine how the max function will decide the value of each player. In this case, you are using a lambda function to say "for each p in players get p.totalscore and use that as his value for comparison".

正如您可以想象的那样,对于一个复杂的对象,比如一个玩家确定它的比较值是很复杂的,所以你会得到一个关键的参数来确定max函数是如何决定每个玩家的价值的。在这种情况下,你使用lambda函数来表示“对于每个p的参与者都得到p”。totalscore并将其用作比较的价值。

#5


4  

max function is used to get the maximum out of an iterable.

max函数被用来从迭代中得到最大的值。

The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.

迭代器可以是列表、元组、命令对象等,甚至可以是您提供的示例中的自定义对象。

max(iterable[, key=func]) -> value
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.

So, the key=func basically allows us to pass an optional argument key to the function on whose basis the the given iterator/arguments are sorted & the maximum is returned.

因此,key=func基本上允许我们传递一个可选的参数键到函数的基础上,给定的迭代器/参数被排序,并且返回最大值。

lambda is a python keyword that acts as a pseudo function. So, when you pass player object to it, it will return player.totalScore. Thus, the iterable passed over to function max will sort according to the key totalScore of the player objects given to it & will return the player who has maximum totalScore.

lambda是一个python关键字,充当pseudo函数。因此,当您将player对象传递给它时,它将返回player. totalscore。因此,迭代传递到函数max将根据给定的player对象的关键totalScore排序,并返回具有最大totalScore的播放器。

If no key argument is provided, the maximum is returned according to default Python orderings.

如果没有提供关键参数,则根据默认的Python命令返回最大值。

Examples -

的例子,

max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7

people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')

#6


0  

max is built in function which takes first argument an iterable (like list or tuple)

max是在函数中构建的,它以第一个参数为可迭代(如列表或元组)

keyword argument key has it's default value None but it accept function to evaluate, consider it as wrapper which evaluates iterable based on function

关键字参数键有它的默认值,但是它接受函数来评估,把它当作是基于函数的可迭代的包装器。

Consider this example dictionary:

考虑一下这个例子字典:

d = {'aim':99, 'aid': 45, 'axe': 59, 'big': 9, 'short': 995, 'sin':12, 'sword':1, 'friend':1000, 'artwork':23}

Ex:

例:

>>> max(d.keys())
'sword'

As you can see if you only pass the iterable without kwarg(a function to key) it is returning maximum value of key(alphabetically)

正如您所看到的,如果您只通过iterable,而没有kwarg(一个函数对键),那么它将返回键的最大值(按字母顺序)

Ex. Instead of finding max value of key alphabetically you might need to find max key by length of key:

不需要按字母顺序查找键的最大值,你可能需要按长度的键找到max键:

>>>max(d.keys(), key=lambda x: len(x))
'artwork'

in this example lambda function is returning length of key which will be iterated hence while evaluating values instead of considering alphabetically it will keep track of max length of key and returns key which has max length

在这个例子中,lambda函数是返回键的长度,它将被迭代,因此在评估值时,而不是按字母顺序考虑,它会跟踪键的最大长度,并返回最大长度的键。

Ex.

前女友。

>>> max(d.keys(), key=lambda x: d[x])
'friend'

in this example lambda function is returning value of corresponding dictionary key which has maximum value

在这个示例中,lambda函数返回对应的字典键值,该值具有最大值。