将列表和字典解压缩到相同的参数中

时间:2017-08-07 11:30:00

标签: python

def foo(l=None, d=None):
    return bar(*l, **d) # eg. bar(1, 2, 3, a=a, b=b)

输入:

l = [1, 2, 3]
d = {'a': a, 'b': b}

foo(l=l, d=d)

lNone时出现问题,即。这个电话是:

foo(d={'a':a})

我在foo更改了哪些内容,以便在列表和字典上轻松处理NoneType

这很难看,必须有比这更好的方法:

def foo(l=None, d=None):
    if l is not None and d is not None:
        return bar(*l, **d)
    if l is not None:
        return bar(*l)
    if d is not None:
        return bar(**d)

3 个答案:

答案 0 :(得分:4)

您可以使用or

与空的iterables短路
def foo(l=None, d=None):
    return bar(*(l or ()), **(d or {}))

或者使其更具可读性,尽管更详细:

def foo(l=None, d=None):
    l = l or ()
    d = d or {}
    return bar(*l, **d)

答案 1 :(得分:2)

使用空元组和空字典作为默认参数,而不是None

def foo(l=(), d={}):
    return bar(*l, **d)

您必须注意不要更改d函数中的foo,因为它是一个可变的默认参数(另请参阅"Least Astonishment" and the Mutable Default Argument)。如果您需要谨慎,可以使用immutable dictionary

from types import MappingProxyType  # requires python 3.3

def foo(l=(), d=MappingProxyType({})):
    return bar(*l, **d)

答案 2 :(得分:-1)

请检查,这会对你有所帮助..

composer.json

输出:

def bar(*mylist, **mydict):
    print mylist
    print mydict


def foo(arg=None, kwarg=None):
    if not isinstance(arg, list):
        arg = []
    if not isinstance(kwarg, dict):
        kwarg = {}
    return bar(*arg, **kwarg)


l = [1, 2, 3]
d  ={'a': 'a', 'b': 'b'}

foo(l,d)
foo(l, None)
foo(None,d)