使用'key'和lambda表达式的python max函数 [英] python max function using 'key' and lambda expression

查看:673
本文介绍了使用'key'和lambda表达式的python max函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自OOP背景并试图学习python。
我使用 max 函数,它使用lambda表达式返回类型为 Player 的实例, totalScore 列表玩家

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

该函数正确返回类型为 Player 的实例,其中最大值为 totalScore
我对以下三件事感到困惑:


  1. max 功能工作?它正在采取什么论据?我查看了文档,但未能理解。

  2. max函数中关键字 key 的用法是什么?我知道它也用于 sort 函数的上下文中
  3. lambda表达式的含义?如何阅读它们?他们是如何工作的?

这些都是非常不理想的概念性问题,但会帮助我理解语言。如果你能举例说明,这将会有所帮助。
谢谢

解决方案

lambda 是一个匿名函数,它相当于:

  def func(p):
返回p.totalScore
max
变为:



>

  max(players,key = func)

但因为 def 语句是复合语句,所以在需要表达式时不能使用它们,这就是为什么有时 lambda 的s被使用。请注意,lambda相当于您放入 def 的返回语句中的内容。因此,您不能在 lambda 内使用语句,只允许表达式。






max做什么?


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

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

因此,它只是返回最大的对象。 / p>




 `key`如何工作? 

默认情况下,Python 2键比较基于一组规则(例如,一个字符串总是大于一个整数)。



要在比较之前修改对象或根据特定属性/索引进行比较,您必须使用论据。

示例1:

一个简单的例子,假设你有一个字符串形式的数字列表,但你想比较这些项目的整数值。

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

code> max 使用它们的原始值比较项目(字符串按照字典顺序进行比较,所以你可以得到'2'作为输出):

 >>> max(lis)
'2'

用一个简单的 lambda

 >>> max(lis,key = lambda x:int(x))#compare每个项目的'int`版本
'111'

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

 >>> (1,'c'),(4,'e'),(-1,'z')] 

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

 >>> ;最大(lis)
(4,'e')

但是,如果你想要比较每个项目的索引值1?很简单,使用 lambda

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






比较包含不同类型对象的迭代中的项目



包含混合项目的列表:

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

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

 >>> max(lis)#在Python 2中工作
'2'
>>> max(lis,key = lambda x:int(x))#compare每个项目的整数版本
'111'

但在Python 3中,您无法做到这一点更多

 >>> lis = ['1','100','111','2',2,2.57] 
>>> max(lis)
Traceback(最近一次调用最后一次):
文件< ipython-input-2-0ce0a02693e4>,第1行,位于< module>
max(lis)
TypeError:无法定义的类型:int()> str()

但是,这是有效的,因为我们正在比较每个对象的整数版本:

 >>> max(lis,key = lambda x:int(x))#或简单地`max(lis,key = int)`
'111'


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.

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:

  1. How does the max function work? 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? I know it is also used in context of sort function
  3. Meaning of the lambda expression? 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:

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.

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.


What does max do?

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, 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).

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

Example 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(lis)
'2'

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

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

Example 2: Applying max to a list of lists.

>>> 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(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple, use 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'

这篇关于使用'key'和lambda表达式的python max函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆