繁体   English   中英

Python - 函数/参数元组列表

[英]Python - list of function/argument tuples

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)

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

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

FUNCTION_LIST[2] = (f2,)
for f,arg in FUNCTION_LIST:
    f(arg)

导致ValueError: need more than 1 value to unpack

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

for n in range(len(FUNCTION_LIST)):
    FUNCTION_LIST[n][0](FUNCTION_LIST[n][1])

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

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

for f,args in FUNCTION_LIST:
    f(*args)

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

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

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

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

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

for f, args in FUNCTION_LIST:
    f(*args)

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

问题是这样的表示法:

(6)

求值为整数值,你需要元组,所以这样写:

(6, )

并且你的星号表示法会成功。

尝试传递*()而不是() *符号告诉python解包后面的迭代,因此它解包空元组并且不传递给函数,因为元组是空的。

为了记录,我发现的一个不错的选择是使用functools.partial 以下代码执行我尝试执行的操作:

from functools import partial

def f1(n): #accepts one argument
    pass

def f2(): #accepts no arguments
    pass

FUNCTION_LIST = [partial(f1,2), #each list entry is a callable with the argument pre-ordained
                 partial(f1,6),
                 partial(f2)] #the call to partial is not really necessary for the entry with no arguments.

for f in FUNCTION_LIST: f()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM