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...


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...