程式扎記: [ Python 常見問題 ] Expanding tuples into arguments

標籤

2016年5月22日 星期日

[ Python 常見問題 ] Expanding tuples into arguments

Source From Here
Question
Is there a way to expand a Python tuple into a function - as actual parameters? For example, here expand() does the magic:
  1. tuple = (1"foo""bar")  
  2.   
  3. def myfun(number, str1, str2):  
  4.     return (number * 2, str1 + str2, str2 + str1)  
  5.   
  6. myfun(expand(tuple)) # (2"foobar""barfoo")  
How-To
myfun(*tuple) does exactly what you request. This is actually very simple to do in Python, simply loop over the list and use the splat operator (*) to unpack the tuple as arguments for the function:
>>> tup = (1, 'foo', 'bar')
>>> def myfun(num, str1, str2):
... return (num*2, str1 + str2, str2 + str1)
...
>>> myfun(*tup)
(2, 'foobar', 'barfoo')

Supplement
[Quick Python] 9. Functions
The Python Tutorial - More Control Flow Tools - Unpacking Argument Lists
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple...


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!