python - 将函数 1 中元组的所有元素(从 *args)传递到 python 中的函数 2(作为 *args)

标签 python function tuples args

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

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

            for x in args:
                align(*x)

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

最佳答案

您可以使用*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)

关于python - 将函数 1 中元组的所有元素(从 *args)传递到 python 中的函数 2(作为 *args),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39175288/

相关文章:

python - 如何在同一 prototxt 中生成用于训练和测试的数据层(HDF5)?

ios - 挣扎于引用变量(Swift)

list - 递归地将元组列表转换为列表元组

更改函数内的指针

C++11 可变模板 : default index array value

python - 从字符串 python 创建单项元组

python - Anaconda Python 配置脚本会与 Homebrew 冲突吗?

Python - 如何显示窗口+打印文本?它只打印但不显示窗口的地方

python - Django 得到了一个意外的关键字参数

javascript - 如何在java脚本中单击后将带有<i>元素的<li>元素添加到<ul>