只需使用func
,删除()
:
min(list,key=func)
例子:
>>> lis = [ '1', '2', '3', '4' ]
>>> def func(x):
... return int(x)
...
>>> min(lis, key=func) # each value from list is passed to `func`(one at a time)
'1'
在 pythonTrue
中等于1
和False
等于0
,所以如果func()
返回布尔值,那么实际上你的min
函数将只比较1
和0
。
>>> True == 1
True
>>> False == 0
True
例子:
>>> def func(x): return bool(x)
>>> lis = [ 1, [], 3, 4 ]
>>> min(lis, key=func) # bool([]) evaluated to False, ie 0
[]
>>> max(lis, key=func)
1
另一个例子:
>>> lis = [[4,5,6], [1,2], [13,1,1,1], [1000]]
>>> def func(x):
... return len(x) #comparisons are done based on this value
...
>>> min(lis, key = func)
[1000]
#equal to
>>> min(lis, key = len)
[1000]