在* args中传递一个元组 [英] passing a tuple in *args

查看:111
本文介绍了在* args中传递一个元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将元组(或列表)作为值(参数)序列传递给函数.然后应将元组作为参数打包到* arg.

I'd like to pass a tuple (or maybe a list) to a function as a sequence of values (arguments). The tuple should be then unpacked as an argument into *arg.

例如,这很清楚:

def func(*args):
    for i in args:
        print "i = ", i

func('a', 'b', 3, 'something')

但是我要做的是:

tup = ('a1', 'a2', 4, 'something-else')
func(tup)

这应该与第一种情况类似. 我想我应该在这里使用转载和评估,但不确定确切的方法.

And this should behave similar to the first case. I think I should use here reprint and eval but not sure how exactly.

我知道我可以在函数中传递元组,然后在体内将其拆包,但是我的问题是如何在函数调用本身中将其拆包.

I know that I can just pass the tuple in the function and then unpack it within the body, but my question here is how to unpack it in the function call itself.

推荐答案

调用函数时,只需使用func(*tup)直接将元组解包即可.

You can just use func(*tup) to unpack the tuple directly when you invoke the function.

>>> func(*tup)
i =  a1
i =  a2
i =  4
i =  something-else

这等效于func(tup[0], tup[1], tup[2], ...).如果该函数需要多个单独的参数,则同样适用:

This is kind of equivalent to func(tup[0], tup[1], tup[2], ...). The same also works if the function expects multiple individual parameters:

>>> def func2(a, b, c, d):
...     print(a, b, c, d)
...
>>> func2(*tup)
('a1', 'a2', 4, 'something-else')

例如参见此处,以获取有关语法的更深入的背景.

See e.g. here for more in-depth background on the syntax.

这篇关于在* args中传递一个元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆