我对编程相当陌生,我已经用Python工作了几个月了。我试图让一个概念与Stackless一起工作,但就是不知道如何使用Stackless(尽管我已经编写了other test scripts来使用Stackless)。在
任何人,作为一个简单的例子,考虑下面的代码,该代码通过递归调用同一个函数来遍历一个列表并找到它的所有排列(编辑:n维笛卡尔积)。在
def traverseList(theList,temp,solutions,level=1):
if level != len(theList):
for x in theList:
temp.append(x)
traverseList(theList,temp,solutions,level+1)
temp.pop()
else:
for x in theList:
temp.append(x)
solutions.append(temp[:])
temp.pop()
myList = ["a",None,2,"gamma",8] #the list doesn't always have just numbers
solutionList = []
tempList = []
traverseList(myList,tempList,solutionList)
print("%s... %s" %(solutionList[0], solutionList[-1]))
结果是:
^{pr2}$到目前为止,我发现的关于Stackless和递归的唯一例子是函数在完成所有操作后在函数的末尾发送信息。永远不要在for循环的中间,就像上面提到的那样。在
我该怎么做?我该如何将其转换为一个使用微线程而不是递归函数运行的脚本?(This version是我能想到的最好的,但是不管我怎么安排它,它都失败了。这是很多次尝试中的一次,此时我不妨把意大利面扔到墙上。)
额外的e-cookie是一种没有反弹功能的方法-我还没有找到一种方法让一个微线程在没有一个函数的情况下将信息多次传递给自己。在
谢谢你的时间!在
我认为您应该研究“generators”(即“yield”python关键字)。基本上,生成器允许您在函数调用过程中暂停并返回结果。当函数再次被“调用”时,它将在“yield”之后的行恢复。当你最终“回来”的时候,你就完成了。在
下面是一些示例代码:
输出如下。注意,在generator case(myGen)中,“in myGen”与列表的打印交替打印。但在myFn中,当然“in myFn”是首先打印出来的。在
^{pr2}$如果我对你的问题理解正确,而且你已经有了自己的方法,那么把这个插进去就行了
或者,您可以在微线程的参数列表中使用*args/**kwargs
相关问题 更多 >
编程相关推荐