开发者

How to find the max object as per some custom criterion?

开发者 https://www.devze.com 2023-01-02 00:40 出处:网络
I can do max(s) to find the max of a sequence. But suppose I want 开发者_如何学Pythonto compute max according to my own function, something like:

I can do max(s) to find the max of a sequence. But suppose I want 开发者_如何学Pythonto compute max according to my own function, something like:

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

Is there a clean pythonic way of doing this?


max(s, key=operator.methodcaller('arity'))

or

max(s, key=lambda x: x.arity())


For instance,

max (i.arity() for i in s)


You can still use the max function:

max_arity = max(s, key=lambda i: i.arity())


I think the generator expression of doublep is better, but we seldom get to use methodcaller, so...

from operator import methodcaller
max(map(methodcaller('arity'), s))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号