Skip to main content
 首页 » 编程设计

python之如何检查 Python 是否存在函数参数

2025年05月04日14lyj

我的代码是:

def load_data(datafile, categories=None, cat_columns=None): 
    ohe_categories = 'auto' 
    if categories and len(categories) > 0: 
        ohe_categories = categories 
    ohe = OneHotEncoder(handle_unknown='ignore', categories=ohe_categories) 

当 categories 为 None 时,它工作正常。但是如果我传递一些东西,我会得到一个错误:

ValueError: The truth value of a Index is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().  

我正在调用函数:

training_x, training_y, categories, cat_columns = loader.load_data( 
    'data/training.csv') 
 
test_x, test_y = loader.load_data( 
    'data/test.csv', categories=categories, cat_columns=cat_columns) 

如何正确检查?

请您参考如下方法:

我建议这样做:

def load_data(datafile, categories=None, cat_columns=None): 
    ohe_categories = 'auto' 
    if categories is not None: 
        if len(categories) > 0: 
            ohe_categories = categories 
    ohe = OneHotEncoder(handle_unknown='ignore', categories=ohe_categories)