Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 支持单个字符串和数组作为一个参数_Python_String_Parameters_Polymorphism_Typing - Fatal编程技术网

Python 支持单个字符串和数组作为一个参数

Python 支持单个字符串和数组作为一个参数,python,string,parameters,polymorphism,typing,Python,String,Parameters,Polymorphism,Typing,I带有附加字符串参数(平均值): 因此,通常的用法是: classification_report(y_true, y_pred, average='micro') 根据对的审查,审查者建议也支持多个值:average=['micro','weighted','macro'] 用Python解决这个问题的合适方法是什么?我知道参数可以有任何类型。但是如何用字符串列表处理潜在的调用呢?参数的类型是什么联合[str,列表[str]] 目前,我只希望看到一个字符串,这是直截了当的。但是,如果我也允许

I带有附加字符串参数(平均值):

因此,通常的用法是:

classification_report(y_true, y_pred, average='micro')
根据对的审查,审查者建议也支持多个值:
average=['micro','weighted','macro']

用Python解决这个问题的合适方法是什么?我知道参数可以有任何类型。但是如何用字符串列表处理潜在的调用呢?参数的类型是什么<代码>联合[str,列表[str]]


目前,我只希望看到一个字符串,这是直截了当的。但是,如果我也允许字符串列表,我是否应该首先用
type(average)
检查类型,然后相应地处理值?是否有一种优雅的方法可以将参数变量转换为统一类型,例如
averages=listify(average)
,它接受字符串或字符串列表并始终返回字符串列表?

以下是pandas的一个示例:

if level is not None:
        if not isinstance(level, (tuple, list)):
            level = [level]

这是来自pandas.DataFrame.reset_index(level=None,drop=False,inplace=False,col_level=0,col_fill='')方法的代码。其中,级别应为
int、str、tuple或list,默认为None
。这个简单的代码只是确保参数现在存储在一个列表中,而不管它是如何给出的。

就我个人而言,我更希望只需要一个字符串序列,如果您只需要一个选项,那么它就是一个带有单个元素的序列。也就是说,如果isinstance(arg,str),您可能只需使用
:handle_string_arg()else:try:for x in arg:…
拥有
listify
函数,只需将
isinstance
检查推到其他地方即可。另外,请不要将列表对象与数组混淆。
if level is not None:
        if not isinstance(level, (tuple, list)):
            level = [level]