Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

python - passing a tuple in *args

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.

For example, this is clear:

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

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

But what I want to do is this:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...