如何处理Python单个val和val列表?

JS.*_*JS. 4 python list

我经常遇到这个问题:我正在创建一个需要对值执行一系列操作的函数,无论该值是单个值还是值列表.

有一种优雅的方式来做到这一点:

def convert_val(val):
   do a series of things to each value, whether list or single val
   return answer or list of answers
Run Code Online (Sandbox Code Playgroud)

而不是我一直在做什么?:

def convert_val(val):
    if isinstance(val, list):
       ... do a series of things to each list item,
       return a list of answers
    else:
       ... do the same series, just on a single value
       return a single answer
Run Code Online (Sandbox Code Playgroud)

一种解决方案是创建一个sub_convert()来执行一系列操作,然后只调用一次或迭代,具体取决于传入convert()的类型.

另一种方法是创建一个接受参数(value,sub_convert())的convert().

其他建议更紧凑,更优雅,最好是一体化?

(我在这里做了几次搜索,看看我的问题是否已经解决.如果有问题,我的意见.)

谢谢,JS

S.L*_*ott 6

您需要修改您的设计,以使该功能的所有使用实际上正确.

拉尔夫沃尔多爱默生."愚蠢的一致性是小脑袋的大人物,小政治家,哲学家和神职人员都崇拜这种思想."

我们不是在谈论愚蠢的一致性.基于此函数的不一致使用,您可能会遇到设计问题.

选项1.不要叫convert_val( x )哪里x是一个非列表.做这个. convert_val( [x] ).不要修复您的功能,修复使用您的功能的所有地方.一致性有助于减少错误.

选项2.更改设计convert_val以使用多个位置参数.这并不能很好地概括.

def convert_val( *args ):
    whatever it's supposed to do to the arguments.
Run Code Online (Sandbox Code Playgroud)

然后修复您提供列表的所有位置convert_val( *someList ).那没关系,可能更接近你的意图.

注意.

您可以使用该warnings模块找到设计错误.

def convert_val( arg ):
    if isinstance( arg, collections.Sequence ):
        return convert_val_list( arg )
    else:
        warnings.warn( "Fix this" )
        return convert_val_list( [arg] )[0]

def convert_val_list( arg ):
    assert isinstance( arg, collections.Sequence )
    the original processing
Run Code Online (Sandbox Code Playgroud)

一旦解决了所有设计问题,就可以执行此操作

convert_val = convert_val_list
Run Code Online (Sandbox Code Playgroud)

并删除原始功能.