使用'key'和lambda表达式的python max函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18296755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python max function using 'key' and lambda expression
提问by Vijay
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 表达式的函数返回列表中Player
具有最大值的类型的实例。totalScore
players
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:
该函数正确返回Player
具有最大值的类型实例totalScore
。我对以下三件事感到困惑:
- How does the
max
function work? What are the arguments it is taking? I looked at the documentation but failed to understand. - What is use of the keyword
key
in max function? I know it is also used in context ofsort
function - Meaning of the lambda expression? How to read them? How do they work?
- 该
max
功能是如何工作的?它的论据是什么?我查看了文档但未能理解。 key
max函数中的关键字有什么用?我知道它也用于sort
函数上下文- 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
这些都是非常菜鸟的概念性问题,但会帮助我理解语言。如果你能举个例子来解释会有所帮助。谢谢
采纳答案by Ashwini Chaudhary
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
's的原因。
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
等效于您在 a 的 return 语句中放入的内容def
。因此,您不能在 a 中使用语句lambda
,只允许使用表达式。
What does max
do?
有什么作用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.
max(a, b, c, ...[, key=func]) -> 值
使用单个可迭代参数,返回其最大的项目。对于两个或更多参数,返回最大的参数。
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 rulesbased on the type of the objects (for example a string is always greater than an integer).
默认情况下,Python 2key
根据一组基于对象类型的规则来比较项目(例如,字符串总是大于整数)。
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. 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
将按第一个索引比较项目。如果第一个索引相同,那么它将比较第二个索引。在我的例子中,所有项目都有一个唯一的第一个索引,所以你会得到这个作为答案:
>>> max(lis)
(4, 'e')
But, what if you wanted to compare each item by the value at index 1? Simple: use lambda
:
但是,如果您想通过索引 1 处的值比较每个项目怎么办?简单:使用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:
>>> 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:
>>> 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'
回答by Markus Unterwaditzer
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
回答by Inbar Rose
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.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.
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)).
max(iterable[, key])
max(arg1, arg2, *args[, key])
返回可迭代对象中最大的项或两个或多个参数中最大的项。如果提供了一个位置参数,则 iterable 必须是非空的可迭代对象(例如非空字符串、元组或列表)。返回迭代中最大的项目。如果提供了两个或更多位置参数,则返回最大的位置参数。
可选的 key 参数指定一个单参数排序函数,就像用于 list.sort() 的那样。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
. Then the max
function will iterate over all the items in the list and compare them to each other to get a "maximum".
这就是说,在你的情况下,你提供了一个列表,在这种情况下players
。然后该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".
可以想象,对于像 a 这样的复杂对象,player
确定其比较值是很棘手的,因此您将获得key
参数来确定max
函数将如何决定每个 的值player
。在这种情况下,您使用的是lambda函数说“每个p
在players
获取p.totalscore
和使用,作为他的比较值”。
回答by charmlessCoin
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关键字的作用是什么?我知道它也用于排序函数的上下文中
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
迭代中的哪些对象比其他对象大。假设您正在对自己创建的某个对象进行排序,而不是对一些显而易见的对象(如整数)进行排序。
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()
take 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 understandit here.
不是那么简单,lambda 来自 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.
多读一点可能会更好,因为 lambda 可能会令人困惑,而且它们的用处并不是很明显。检查这里。
回答by shad0w_wa1k3r
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 the the given iterator/arguments are sorted & the maximum is returned.
因此,key=func
基本上允许我们将可选参数传递key
给函数,根据该函数对给定的迭代器/参数进行排序并返回最大值。
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
totalScoreof the player
objects given to it & will return the player
who has maximum totalScore
.
lambda
是一个 python 关键字,用作伪函数。因此,当您将player
对象传递给它时,它将返回player.totalScore
. 因此,传递给函数的可迭代对象max
将根据提供给它的对象的key
totalScore进行排序,player
并返回player
拥有最大值的对象totalScore
。
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')
回答by Gahan
max
is built in function which takes first argument an iterable
(like list or tuple)
max
内置函数,它接受第一个参数 an 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(a function to key
)的 iterable,它会返回 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 函数返回具有最大值的相应字典键的值