简言之。除此之外,我该怎么写:for another in combinationOfK(K-1, L[i+1:]):
我的函数combinationOfK(…)是不可编辑的。在
我试图理解here中的代码,解决方案。Problem 26: Generate the combinations of K distinct objects chosen from the N elements of a list
我知道产量的作用。但是我试图在不使用语句的情况下编写代码。代码和yield语句就是这样。在
def combination(K, L):
if K<=0:
yield []
return
for i in range(len(L)):
thisone = L[i:i+1]
for another in combination(K-1, L[i+1:]):
yield thisone + another
The question, ^{
When you see a function with
yield
statements, apply this easy trick to understand what will happen:
- Insert a line
result = []
at the start of the function.- Replace each
yield expr
withresult.append(expr)
.- Insert a line
return result
at the bottom of the function.- Yay - no more
yield
statements! Read and figure out code.- Revert function to original definition.
用这个来获取代码而不产生收益给我这个。代码不工作(函数不可编辑)。我要写些什么才能让这段代码毫无收获地工作?
^{pr2}$我用这段代码来测试函数
the_list = ['a','b','c','d','e']
print list(combinationOfK(2, the_list))
引发错误TypeError: 'NoneType' object is not iterable
。在
问题是您的原始代码以一种不寻常的方式使用
return
。在大多数情况下,您不会在生成器中看到
return
,因为您不经常需要它。通常,生成器只是在末尾“掉下来”;解释器到达生成器的末尾时没有遇到return
语句,然后它知道抛出StopIteration
。在在这个案例中,代码的编写者插入了一个
^{pr2}$return
语句来“加快”进程。当K <= 0
时,没有更多的工作要做,因此生成器可以抛出StopIteration
,但是如果没有return
语句,它将进入for
循环,产生错误的结果。在我看来,更清楚的方法应该是:现在转换按预期工作:
正如文森特提到的,由于第五行,您的函数没有返回任何值。将其更改为:
但是,你为什么反对收益?生成器可以生成可读、高效的代码。Yield关键字Explained这篇文章的重点并不是要放弃它,而是要解释它。在
在您发布的生成器代码中:
^{pr2}$return
语句与return
在普通函数中的含义不同。在生成器中,return
立即引发StopIteration,这将导致调用者停止对生成器对象的迭代。在相关问题 更多 >
编程相关推荐