用于计算百分位数的纯python实现:这里使用lambda函数是什么?

jov*_*v14 3 python lambda median percentile

我在这里这里偶然发现了用于计算百分位数的纯python实现:

import math
import functools

def percentile(N, percent, key=lambda x:x):
"""
Find the percentile of a list of values.

@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - optional key function to compute value from each element of N.

@return - the percentile of the values
"""
   if not N:
       return None
   k = (len(N)-1) * percent
   f = math.floor(k)
   c = math.ceil(k)
   if f == c:
       return key(N[int(k)])
   d0 = key(N[int(f)]) * (c-k)
   d1 = key(N[int(c)]) * (k-f)
   return d0+d1
Run Code Online (Sandbox Code Playgroud)

我得到了这个函数背后的基本原理,我发现它正常工作:

>>> percentile(range(10),0.25)
2.25
Run Code Online (Sandbox Code Playgroud)

我没有得到的是lambda函数key=lambda x:x的用途.至于我解释它,这个lambda函数只返回传递给它的值.基本上,如果我完全省略这个lambda函数,整个函数似乎产生相同的结果:

import math

def percentile2(N, percent):
"""
Find the percentile of a list of values.

@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - REMOVED

@return - the percentile of the values
"""
   if not N:
       return None
   k = (len(N)-1) * percent
   f = math.floor(k)
   c = math.ceil(k)
   if f == c:
       return N[int(k)]
   d0 = N[int(f)] * (c-k)
   d1 = N[int(c)] * (k-f)
   return d0+d1
Run Code Online (Sandbox Code Playgroud)

如果我测试一下:

>>> percentile2(range(10),0.25)
2.25
Run Code Online (Sandbox Code Playgroud)

那么这个lambda函数有什么用?

Rob*_*tts 7

答案就在docstring(def语句后面的行开头的字符串)中:

@parameter key - optional key function to compute value from each element of N.
Run Code Online (Sandbox Code Playgroud)

这允许您使用除数字之外的其他内容的列表.例如,您的lambda可能是lambda x:x.getRelevantValue(),您的列表将包含具有getRelevantValue方法的对象.