How do I pass tuples elements to a function as arguments?

后端 未结 2 540
心在旅途
心在旅途 2020-12-11 01:47

I have a list consisting of tuples, I want to pass each tuple\'s elements to a function as arguments:

mylist = [(a, b), (c, d), (e, f)]

myfunc(a, b)
myfunc(         


        
相关标签:
2条回答
  • 2020-12-11 02:14

    To make @DSM's comment explicit:

    >>> from itertools import starmap
    >>> list(starmap(print, ((1,2), (3,4), (5,6)))) 
    # 'list' is used here to force the generator to run out.
    # You could instead just iterate like `for _ in starmap(...): pass`, etc.
    1 2
    3 4
    5 6
    [None, None, None] # the actual created list;
    # `print` returns `None` after printing.
    
    0 讨论(0)
  • 2020-12-11 02:26

    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:

    mylist = [(a, b), (c, d), (e, f)]
    for args in mylist:
        myfunc(*args)
    

    E.g:

    >>> numbers = [(1, 2), (3, 4), (5, 6)]
    >>> for args in numbers:
    ...     print(*args)
    ... 
    1 2
    3 4
    5 6
    
    0 讨论(0)
提交回复
热议问题