How to find the max object as per some custom criterion?
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))
精彩评论