首页 文章

将元组扩展为参数

提问于
浏览
298

有没有办法将Python元组扩展为函数 - 作为实际参数?

例如,这里 expand() 做了魔术:

tuple = (1, "foo", "bar")

def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)

myfun(expand(tuple)) # (2, "foobar", "barfoo")

我知道可以将 myfun 定义为 myfun((a, b, c)) ,但当然可能有遗留代码 . 谢谢

5 回答

  • 6

    myfun(*tuple) 确实 exactly 您的要求 .

    附带问题: don't 用作你的标识符内置类型名称,如 tuplelistfileset 等等 - 这是一种可怕的做法,它会在你最不期望的时候回来咬你,所以要养成习惯主动避免使用您自己的标识符隐藏内置名称 .

  • 32

    请注意,您还可以展开参数列表的一部分:

    myfun(1, *("foo", "bar"))
    
  • 13

    看看the Python tutorial 4.7.3和4.7.4节 . 它讨论了将元组作为参数传递 .

    我还会考虑使用命名参数(并传递字典)而不是使用元组并传递序列 . 当位置不直观或有多个参数时,我发现使用位置参数是一种不好的做法 .

  • 0

    这是函数式编程方法 . 它提取了语法糖中的元组扩展功能:

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

    用法示例:

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

    curry重新确定 apply_tuple 从长远来看,可以节省很多 partial 次来电 .

  • 565

    我遇到了类似的问题并创建了这个扩展固定功能的功能 . 希望这可以帮助 .

    def run_argtup(func, argvalues):
        """
        Execute any functions with their arguments in tuple.
    
        :param func:
        :param argvalues:
        :return:
        """
        argnames = get_func_argnames(func)
        if len(argnames) != len(argvalues):
            raise ValueError("Length of args doens't match.")
        for argn, argv in zip(argnames, argvalues):
            exec('{}=argv'.format(argn))
        return eval('func(%s, %s)' % argnames)
    

相关问题