I w*_*ges 0 python nested function
我将解释这个例子,因为它更容易描述这种方式:
假设我们有一个未确定的(X)变量数,可以是列表或字符串.
例如,X = 3,我们有:
Var1=list("a","b")
Var2=list("c","d")
Var3="e"
所有这些都在一个列表中:ListOfVariables = [Var1,Var2,Var3]
然后我们在这些变量上运行一个函数(我们事先不知道这个函数,但它使用的是我们拥有的相同数量X的变量).
def Function(Var1,Var2,Var3)
    print Var1
    print Var2
    print Var3
这里的目标是使函数与所有输入变量一起运行,如果其中一个是列表,它必须为列表中的每个项执行Function.所以想要的结果就是为所有这些调用Function,如下所示:
Function(a,c,e)
Function(a,d,e)
Function(b,c,e)
Function(b,d,e)
到目前为止,我使用一个辅助函数来识别Var1,Var2和Var3,但是我的大脑没有那么多的递归可预测性,因为能够定义这个HelperFunction,例如:
def HelperFunction():
    for item in ListOfVariables:
        if type(item).__name__=='list':
            #This one will be done as a "for", so all the items in this list are executed as input (Var1 and Var2 in the example)
        else:
            #This item doesnt need to be included in a for, just execute once (Var3 in the example)
我知道它可以用python完成,但我不能在脑海中编写我需要的功能,它比我的"大脑模拟器"更复杂一度可以模拟python =(
非常感谢您的帮助.
非常感谢您的答案,但我不确定提议的解决方案是否解决了问题.如果我们运行:
helper_function(ListOfVariables)
然后helper_function应该调用函数"Function"4次,如下所示:
Function(a,c,e)
Function(a,d,e)
Function(b,c,e)
Function(b,d,e)
目的是使用输入中的所有变量,BUT在函数需要的相应位置.更具体地说,helper_function(ListOfVariables)的逻辑过程是:
Var1是一个列表,因此,我将不得不遍历其包含并运行Function(),但这些只是函数的第一个参数!
Var2是一个列表,因此,我也将循环,项目只是Function()的第二个参数
Var3是单个项目,因此,对于其他两个循环,此值将被赋予常量.
这就是我们如何获得所需:
Function(a,c,e)
Function(a,d,e)
Function(b,c,e)
Function(b,d,e)
非常感谢,我不能自己解决这个问题!
如果我正确理解你,那么进一步概括问题:你想在参数中的所有元素的乘积上迭代函数; 非列表参数应被视为仅包含自身的列表.使用该itertools模块,并将其视为迭代而非递归过程简化了以下事项:
import itertools
def combine(*args):
    lists = [arg if isinstance(arg, list) else [arg] for arg in args]
    for a, b, c in itertools.product(*lists):
        Function(a, b, c)
Var1=["a","b"]
Var2=["c","d"]
Var3="e"
combine(Var1, Var2, Var3)
如果您需要处理列表列表,那么您需要一个递归过程.
| 归档时间: | 
 | 
| 查看次数: | 157 次 | 
| 最近记录: |