根据某些自定义标准在python中查找max

MK.*_*MK. 11 python

我可以做max(s)来找到序列的最大值.但是假设我想根据自己的函数计算max,就像这样 -

currmax = 0
def mymax(s) :
  for i in s :
    #assume arity() attribute is present
    currmax = i.arity() if i.arity() > currmax else currmax
Run Code Online (Sandbox Code Playgroud)

这样做有干净的pythonic方法吗?

谢谢!

Ign*_*ams 27

max(s, key=operator.methodcaller('arity'))
Run Code Online (Sandbox Code Playgroud)

要么

max(s, key=lambda x: x.arity())
Run Code Online (Sandbox Code Playgroud)

  • 这就是它所要求的标题听起来,但是发布的代码找到了`i.arity()`的值,而不是`i`的值. (3认同)

dou*_*lep 11

例如,

max (i.arity() for i in s)
Run Code Online (Sandbox Code Playgroud)

  • 这与+1匹配OP中代码的结果 (2认同)

Joh*_*rra 7

你仍然可以使用这个max功能:

max_arity = max(s, key=lambda i: i.arity())
Run Code Online (Sandbox Code Playgroud)