如何根据自定义标准找到最大对象?
我可以用 max(s)
来找出一个序列中的最大值。但是假设我想根据我自己的函数来计算最大值,比如说:
currmax = 0
def mymax(s):
for i in s :
#assume arity() attribute is present
currmax = i.arity() if i.arity() > currmax else currmax
有没有什么简单又优雅的方法在Python中做到这一点呢?
4 个回答
9
你仍然可以使用 max
这个函数:
max_arity = max(s, key=lambda i: i.arity())
12
比如说,
max (i.arity() for i in s)
41
max(s, key=operator.methodcaller('arity'))
或者
max(s, key=lambda x: x.arity())