我们如何从args和kwargs中打印争论列表?

问题描述 投票:0回答:2

假设我们具有可变函数,例如以下内容:

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   
python python-3.x parameter-passing variadic-functions
2个回答
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'

0
投票

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

def foo(*args, **kwargs):
    print(args + tuple('{} = {}'.format(key,val) for key,val in kwargs.items()))
© www.soinside.com 2019 - 2024. All rights reserved.