【发布时间】:2020-02-13 12:19:32
【问题描述】:
我想在满足条件时执行具有不同参数的多个函数,但我从来没有执行过它们中的任何一个:
conditions = [condition1, condition2, condition3]
functions = [lambda: self._f(), lambda x: self._f2(a), lambda x,y: self._f3(b, c)]
for condition, function in zip(conditions, functions):
if condition:
function() # execute the proper function with 0, 1 or 2 arguments
break
def _f():
print('function1 with no arguments')
def _f2(x):
print(f'function2 with one argument {x}')
def _f3(x, y):
print(f'function2 with two arguments {x} and {y}')
但是当条件满足时,不执行相应的函数。我做错了什么??
提前谢谢你!!
【问题讨论】:
-
break退出整个for循环 -
您的第一个 lambda 不会调用
self._f使用self._f() -
什么是
type? `conditions =行在语法上不是写的有效 -
通过以上所有注释,您可以简化:
condition = lambda x: x in ['YES', 'MAYBE', 'TRY AGAIN'],然后通过condition(type)调用它。此外,您知道 conditions 在定义时进行评估,之后更改 type 对它没有任何影响。 -
我真正的问题,独立于变量和条件,是如何定义带有可变参数的函数并用唯一的语句()调用它们
标签: python python-3.x list lambda list-comprehension