Passing functions which have multiple return values as arguments in Python

前端 未结 3 487
忘掉有多难
忘掉有多难 2021-01-01 19:57

So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.

a = [[         


        
3条回答
  •  温柔的废话
    2021-01-01 20:42

    Try this:

    >>> def cord():
    ...     return (1, 1)
    ...
    >>> def printa(y, x):
    ...     print a[y][x]
    ...
    >>> a=[[1,2],[3,4]]
    >>> printa(*cord())
    4
    

    The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars:

    >>> a = {'a' : 2, 'b' : 3}
    >>> def foo(a, b):
    ...    print a, b
    ...
    >>> foo(**a)
    2 3
    

提交回复
热议问题