我们如何从args和kwargs打印参数列表?

时间:2019-10-21 21:47:41

标签: python python-3.x parameter-passing variadic-functions

假设我们具有可变函数,例如:

def foo(*args, **kwargs):
    pass

我想编辑foo,以便它打印参数列表。例如,我们需要以下代码...

foo(98, 99, 100, a = 1, b = 2, c = 3)

...打印...

98, 99, 100, a = 1, b = 2, c = 3   

2 个答案:

答案 0 :(得分:3)

这几乎可以满足您的需求:

def foo(*args, **kwargs):
    print(args + tuple('{} = {}'.format(key,val) for key,val in kwargs.items()))

答案 1 :(得分:0)

以下似乎可以解决问题:

import itertools

rep_kwarg = lambda kwarg: kwarg[0] + " = " + str(kwarg[1])

def foo(*args, **kwargs):
    kwargs2 = map(rep_kwarg, kwargs.items())
    it_combo = itertools.chain(args, kwargs2)
    it_combo_str = map(str, it_combo)
    arg_list = ', '.join(it_combo_str)
    print("RESULT == ", repr(arg_list))


args = [98, 99, 100]
kwargs = {
    "a": 1,
    "b": 2,
    "c": 3
}
foo(*args, **kwargs)
foo(98, 99, 100, a = 1, b = 2, c = 3)

控制台输出为:

RESULT ==  '98, 99, 100, a = 1, b = 2, c = 3'
RESULT ==  '98, 99, 100, a = 1, b = 2, c = 3'