迭代函数参数

2024-10-03 15:30:39 发布

您现在位置:Python中文网/ 问答频道 /正文

目的是建立一个函数,以便在机器学习项目中构造训练集。我有几个特性,我想尝试(单独,2乘2,组合…),所以我把它们作为函数参数。在

我还添加了一个字典来调用所选功能集的“导入函数”。在

例如,如果我选择导入集合“features1”,我将调用import_features1()。在

我无法迭代函数参数。我尝试使用**kwargs,但它没有按我预期的那样工作。在

我的职能是:

def construct_XY(features1=False, features2=False, features3=False, **kwargs):
    #  -- function dict
    features_function = {features1: import_features1,
                         features2: import_features2,
                         features3: import_features3}
    # -- import target
    t_target = import_target()

    # -- (trying to) iterate over parameters
    for key, value in kwargs.items():
        if value is True:
            t_features = features_function(key)()
    # -- Concat chosen set of features with the target table
            t_target = pd.concat([t_target, t_features], axis=1)

    return t_target

我应该按照建议使用locals()here?在

我错过了什么?在


Tags: key函数import目的机器falsetargetvalue
1条回答
网友
1楼 · 发布于 2024-10-03 15:30:39

你可能想用这样的东西

# Only accepts keyword attributes
def kw_only(**arguments):
    # defaults
    arguments['features1'] = arguments.get('features1', False)
    arguments['features2'] = arguments.get('features2', False)
    arguments['features3'] = arguments.get('features3', False)

    for k, v in arguments.items():
        print (k, v)

print(kw_only(one=1, two=2))

使用这种结构,您需要在函数中定义默认值。您将只能传入关键字参数,并且能够迭代所有这些参数。在

相关问题 更多 >