Expanding tuples into arguments

后端 未结 5 1576
逝去的感伤
逝去的感伤 2020-11-22 11:39

Is there a way to expand a Python tuple into a function - as actual parameters?

For example, here expand() does the magic:

some_tuple =          


        
5条回答
  •  萌比男神i
    2020-11-22 12:39

    This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:

    apply_tuple = lambda f, t: f(*t)
    

    Redefine apply_tuple via curry to save a lot of partial calls in the long run:

    from toolz import curry
    apply_tuple = curry(apply_tuple)
    

    Example usage:

    from operator import add, eq
    from toolz import thread_last
    
    thread_last(
        [(1,2), (3,4)],
        (map, apply_tuple(add)),
        list,
        (eq, [3, 7])
    )
    # Prints 'True'
    

提交回复
热议问题