首页 > 解决方案 > 在自定义函数参数中将列表的值设为布尔值

问题描述

我有一个给定的列表和一个带有一些参数的自定义函数。该列表包含字符串形式的参数,我想将这些参数更改为 True 如果列表包含 else 在函数中保持错误。

这是示例:

list_params = ['remove_digits','remove_stopwords','clean_data']

custom_function(remove_digits =False, clean_data =False, remove_stopwords = False, text_lemmatization =False)

这里所有参数首先为假,但一旦列表包含这些参数,在函数中将它们选择为 True,否则保持为假。我想要all the parameters to True at once if present in list

标签: pythonpython-3.x

解决方案


假设您的函数定义类似于:

def custom_function(remove_digits=False, clean_data=False, remove_stopwords=False, text_lemmatization=False):

所以你想“打开”列表中的参数。您可以通过将列表转换为kwargsdict并将其解压缩到函数调用来做到这一点:

list_params = ['remove_digits','remove_stopwords','clean_data']
dict_params = {param: True for param in list_params}

custom_function(**dict_params)

推荐阅读