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

pure python implementation for calculating percentiles: what is the use of the lambda function here?

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

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

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

>>> percentile(range(10),0.25)
2.25

我不明白 lambda 函数 key=lambda x:x 的用途。 据我所知,这个 lambda 函数只是 returns 传递给它的值。基本上,如果我完全省略这个 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

如果我测试这个:

>>> percentile2(range(10),0.25)
2.25

那么这里的 lambda 函数有什么用呢?

万一 f 等于 c,这就是决胜局。你没有遇到过这种情况,所以你的代码永远不会崩溃(因为 key now 不存在)。

答案就在文档字符串中(从 def 语句之后的行开始的字符串):

@parameter key - optional key function to compute value from each element of N.

这允许您使用数字以外的列表。例如,您的 lambda 可以是 lambda x:x.getRelevantValue() 而您的列表将是一个包含具有 getRelevantValue 方法的对象的列表。

它就在函数的文档中:

@parameter key - optional key function to compute value from each element of N.

基本上,percentile 函数允许用户可选地 传递将应用于 N 的元素的键函数。由于它是可选的,因此它具有被赋予了默认值 lambda x:x,它什么都不做,所以即使用户省略了 key 参数,该函数也能正常工作。