Python - 函数/参数元组列表

Ben*_*son 6 python arguments tuples function list

def f1(n): #accepts one argument
    pass

def f2(): #accepts no arguments
    pass

FUNCTION_LIST = [(f1,(2)), #each list entry is a tuple containing a function object and a tuple of arguments
                 (f1,(6)),
                 (f2,())]

for f, arg in FUNCTION_LIST:
    f(arg)
Run Code Online (Sandbox Code Playgroud)

循环中的第三轮,它尝试将一个空的参数元组传递给一个不接受任何参数的函数.它给出了错误TypeError: f2() takes no arguments (1 given).前两个函数调用正常工作 - 元组的内容被传递,而不是元组本身.

摆脱违规列表条目中的空元组参数并不能解决问题:

FUNCTION_LIST[2] = (f2,)
for f,arg in FUNCTION_LIST:
    f(arg)
Run Code Online (Sandbox Code Playgroud)

结果ValueError: need more than 1 value to unpack.

我也试过迭代索引而不是列表元素.

for n in range(len(FUNCTION_LIST)):
    FUNCTION_LIST[n][0](FUNCTION_LIST[n][1])
Run Code Online (Sandbox Code Playgroud)

TypeError在第一种情况下给出相同的,并且IndexError: tuple index out of range当列表的第三个条目是时(f2,).

最后,星号表示法也不起作用.这次调用时出错f1:

for f,args in FUNCTION_LIST:
    f(*args)
Run Code Online (Sandbox Code Playgroud)

TypeError: f1() argument after * must be a sequence, not int.

我已经没事了.我仍然认为第一个应该工作.谁能指出我正确的方向?

Sve*_*ach 9

您在此代码段中的评论显示了与此相关的误解:

FUNCTION_LIST = [(f1,(2)), #each list entry is a tuple containing a function object and a tuple of arguments
                 (f1,(6)),
                 (f2,())]
Run Code Online (Sandbox Code Playgroud)

表达(2)(6)不元组-它们都是整数.您应该使用(2,)(6,)表示您想要的单元素元组.修复此问题后,您的循环代码应如此:

for f, args in FUNCTION_LIST:
    f(*args)
Run Code Online (Sandbox Code Playgroud)

有关语法的说明,请参阅Python教程中的解压缩参数列表*args.