0

我有以下课程

def get_percentile(obs,*args):
    lstper = []
    for arg in args:
        lstper.append(np.percentile(obs,arg))
    return lstper

get_percentile([1,2,3,4,5],25,50,75)
[2.0, 3.0, 4.0]

class Metric(object):
    def __init__(self,*args):
        self.max = max(args)
        self.median =np.median(args)
        self.min = min(args)
        self.percentile = get_percentile(args)

我无法理解正确的集合self.percentile = get_percentile(args)以获得各种百分位数

4

1 回答 1

1

解决此问题的一种方法是使用命名关键字参数而不是*args

def get_percentile(obs,*args):
    if len(args) == 0:
        args = [25,50,75] # default to quartiles
    lstper = []
    for arg in args:
        lstper.append(np.percentile(obs,arg))
    return lstper

class Metric(object):
    def __init__(self, values=[], percentiles=[]):
        self.max = max(values)
        self.median =np.median(values)
        self.min = min(values)
        self.percentile = get_percentile(values, percentiles)

在行动:

>>> m = Metric(range(30,300,13), [20,40,60,80])
>>> m.max
290
>>> m.percentile
[[82.0, 134.0, 186.0, 238.0]]

或者,如果您想继续使用args,您可以在列表(或元组、字典、集合...)中给出值和百分位数。这是必要的,否则无法判断一个结束,另一个开始:

class Metric(object):
    def __init__(self, *args):
        if not len(args) == 2:
            raise ValueError("Usage: Metric([values],[percentiles])")
        values, percentiles = args
        self.max = max(values)
        self.median =np.median(values)
        self.min = min(values)
        self.percentile = get_percentile(values, percentiles)

用法同上。

于 2013-02-25T15:56:53.477 回答