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

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

假设我们有一个可变参数函数,如下所示:

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
3个回答
3
投票

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

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

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(*[f"{v!r}" for v in args],
          *[f"{k} = {v!r}" for k, v in kwargs.items()],
          sep=", ")

使用中:

Python 3.12.3 (main, Sep 11 2024, 14:17:37) [GCC 13.2.0]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.20.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: def foo(*args, **kwargs):
   ...:     print(*[f"{v!r}" for v in args],
   ...:           *[f"{k} = {v!r}" for k, v in kwargs.items()],
   ...:           sep=", ")
   ...:

In [2]: foo(98, 99, 100, a = 1, b = 2, c = 3)
98, 99, 100, a = 1, b = 2, c = 3
© www.soinside.com 2019 - 2024. All rights reserved.