简体   繁体   English

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

[英]python max function using 'key' and lambda expression

I come from OOP background and trying to learn python.我来自 OOP 背景并试图学习 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 .我现在用的max ,它使用lambda表达式返回类型的实例函数Player有最大totalScore名单中players

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

The function correctly returns instance of type Player having maximum totalScore .该函数正确返回具有最大totalScore Player类型的实例。 I am confused about the following three things:我对以下三件事感到困惑:

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

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谢谢

lambda is an anonymous function, it is equivalent to: lambda是一个匿名函数,它等价于:

def func(p):
   return p.totalScore     

Now max becomes:现在max变为:

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 .请注意, lambda等同于您放入def的 return 语句中的内容。 Thus, you can't use statements inside a lambda , only expressions are allowed.因此,您不能在lambda使用语句,只允许使用表达式。


What does max do? max做什么的?

max(a, b, c, ...[, key=func]) -> value max(a, b, c, ...[, key=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 the largest.因此,它只是返回最大的对象。


How does key work? key如何工作的?

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 中, key根据一基于对象类型的规则来比较项目(例如,字符串总是大于整数)。

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.要在比较之前修改对象,或根据特定属性/索引进行比较,您必须使用key参数。

Example 1:示例 1:

A simple example, suppose you have 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 :要按整数值比较项目,请使用key和简单的lambda

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

Example 2: Applying max to a list of tuples.示例 2:将max应用于元组列表。

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

By default max will compare the items by the first index.默认情况下max将按第一个索引比较项目。 If the first index is the same then it'll compare the second index.如果第一个索引相同,那么它将比较第二个索引。 As in my example, all items have a unique first index, so you'd get this as the answer:在我的例子中,所有项目都有一个唯一的第一个索引,所以你会得到这个作为答案:

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

But, what if you wanted to compare each item by the value at index 1?但是,如果您想通过索引 1 处的值比较每个项目怎么办? Simple: use lambda :简单:使用lambda

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

Comparing items in an iterable that contains objects of different type :比较包含不同类型对象的迭代中的项目

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'

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

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, ie a list or string.我假设您可以查找它是什么,但如果不是,则您可以遍历它,即列表或字符串。

What is use of the keyword key in max function? max函数中key关键字的作用是什么? I know it is also used in context of sort function我知道它也用于排序函数的上下文中

Key is a lambda function that will tell max which objects in the iterable are larger than others. Key是一个 lambda 函数,它会告诉max可迭代对象中的哪些对象比其他对象大。 Say if you were sorting some object that you created yourself, and not something obvious, like integers.假设您正在对自己创建的某个对象进行排序,而不是对一些显而易见的对象(如整数)进行排序。

Meaning of the lambda expression? lambda 表达式的含义? How to read them?如何阅读它们? How do they work?它们是如何工作的?

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.简单来说,lambda 是一个可以传递的函数,并且可以让其他代码片段使用它。 Take this for example:以这个为例:

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

This takes two objects, a and b , and a function f .这需要两个对象ab以及一个函数f It calls f() on each object, then adds them together.它对每个对象调用f() ,然后将它们相加。 So look at this call:所以看看这个调用:

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

sum() takes 2 , and calls the lambda expression on it. sum()接受2 ,并在其上调用 lambda 表达式。 So f(a) becomes 2 * 2 , which becomes 4. It then does this for b , and adds the two together.所以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;不是那么简单,lambda 来自 lambda 演算,这是一个函数返回一个函数的思想; a very cool math concept for expressing computation.一个非常酷的数学概念,用于表达计算。 You can read about that here , and then actually understand it here .您可以在此处阅读相关内容,然后在此处真正理解它。

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.多读一点可能会更好,因为 lambdas 可能会令人困惑,而且它们的用处并不是很明显。 Check here .检查这里

max function is used to get the maximum out of an iterable . max函数用于从iterable获取最大值。

The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.迭代器可能是列表、元组、dict 对象等。甚至是您提供的示例中的自定义对象。

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 is the given iterator/arguments are sorted & the maximum is returned.因此, key=func基本上允许我们将可选参数key传递给函数,该函数的基础是给定的迭代器/参数被排序并返回最大值。

lambda is a python keyword that acts as a pseudo function. lambda是一个 Python 关键字,用作伪函数。 So, when you pass player object to it, it will return player.totalScore .因此,当您将player对象传递给它时,它将返回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 .因此,传递给函数max的可迭代对象将根据提供给它的player对象的key totalScore进行排序,并将返回具有最大totalScoreplayer

If no key argument is provided, the maximum is returned according to default Python orderings.如果未提供key参数,则根据默认 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')

According to the documentation :根据文档

max(iterable[, key])最大(可迭代[,键])
max(arg1, arg2, *args[, key]) max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.返回可迭代对象中最大的项或两个或多个参数中最大的项。

If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list).如果提供了一个位置参数,则 iterable 必须是非空的可迭代对象(例如非空字符串、元组或列表)。 The largest item in the iterable is returned.返回迭代中最大的项目。 If two or more positional arguments are provided, the largest of the positional arguments is returned.如果提供了两个或更多位置参数,则返回最大的位置参数。

The optional key argument specifies a one-argument ordering function like that used for list.sort().可选的 key 参数指定一个单参数排序函数,就像用于 list.sort() 的那样。 The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)). key 参数(如果提供)必须采用关键字形式(例如,max(a,b,c,key=func))。

What this is saying is that in your case, you are providing a list, in this case players .这就是说,在您的情况下,您提供了一个列表,在本例中为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 .可以想象,对于像player这样的复杂对象,确定其值进行比较是很棘手的,因此您将获得key参数来确定max函数将如何决定每个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".在这种情况下,您使用 lambda 函数说“对于players每个p获得p.totalscore并将其用作他的比较值”。

max is built in function which takes first argument an iterable (like list or tuple) max是内置函数,它的第一个参数是一个iterable (如列表或元组)

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关键字参数key有它的默认值None但它接受函数来评估,将其视为基于函数评估可迭代的包装器

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)正如你所看到的,如果你只传递没有 kwarg 的迭代(一个函数给key )它会返回 key 的最大值(按字母顺序)

Ex.前任。 Instead of finding max value of key alphabetically you might need to find max key by length of key:您可能需要按键的长度查找最大键,而不是按字母顺序查找键的最大值:

>>>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 函数返回具有最大值的相应字典键的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM