【问题标题】:Passing all elements of tuple in function 1 (from *args) into function 2 (as *args) in python将函数1(来自*args)中元组的所有元素传递给python中的函数2(作为*args)
【发布时间】:2016-08-26 22:10:30
【问题描述】:

我正在编写一个函数来获取 *args 输入,评估数据,然后将所有输入传递给下一个适当的函数(对齐),同时获取 *args

*args 似乎是一个元组。我尝试了各种将元组的每个元素传递给下一个函数的方法,最新的两种方法是:

            for x in args:
                align(*x)

            for x in args:
                align(args[0:len(args)])    

【问题讨论】:

  • 嗯,align(*args)?

标签: python function tuples args


【解决方案1】:

您使用*args“解压”它们。然后接收函数可以再次将它们拖入一个元组(或不!)。

这些例子应该能启发一些事情:

>>> def foo(*f_args):
...     print('foo', type(f_args), len(f_args), f_args)
...     bar(*f_args)
...     
>>> def bar(*b_args):
...     print('bar', type(b_args), len(b_args), b_args)
...     
>>> foo('a', 'b', 'c')
('foo', <type 'tuple'>, 3, ('a', 'b', 'c'))
('bar', <type 'tuple'>, 3, ('a', 'b', 'c'))

现在,让我们重新定义 bar 并打破 argspec:

>>> def bar(arg1, arg2, arg3):
...     print('bar redefined', arg1, arg2, arg3)
...     
>>> foo('a', 'b', 'c')
('foo', <type 'tuple'>, 3, ('a', 'b', 'c'))
('bar redefined', 'a', 'b', 'c')
>>> foo('a', 'b')
('foo', <type 'tuple'>, 2, ('a', 'b'))
---> TypeError: bar() takes exactly 3 arguments (2 given)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 2020-08-09
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多