用iterab替换函数

2024-10-04 03:29:20 发布

您现在位置:Python中文网/ 问答频道 /正文

简言之。除此之外,我该怎么写: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:

  1. Insert a line result = [] at the start of the function.
  2. Replace each yield expr with result.append(expr).
  3. Insert a line return result at the bottom of the function.
  4. Yay - no more yield statements! Read and figure out code.
  5. 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。在


Tags: ofthe函数代码in编辑foranother
2条回答

问题是您的原始代码以一种不寻常的方式使用return。在

def combination(K, L):
    if K<=0:
        yield []
        return    #  < - hmmm

大多数情况下,您不会在生成器中看到return,因为您不经常需要它。通常,生成器只是在末尾“掉下来”;解释器到达生成器的末尾时没有遇到return语句,然后它知道抛出StopIteration。在

这个案例中,代码的编写者插入了一个return语句来“加快”进程。当K <= 0时,没有更多的工作要做,因此生成器可以抛出StopIteration,但是如果没有return语句,它将进入for循环,产生错误的结果。在我看来,更清楚的方法应该是:

^{pr2}$

现在转换按预期工作:

def combination2(K, L):
    result = []
    if K <= 0:
        result.append([])
    else:
        for i in range(len(L)):
            thisone = L[i:i + 1]
            for another in combination2(K - 1, L[i + 1:]):
                result.append(thisone + another)
    return result

正如文森特提到的,由于第五行,您的函数没有返回任何值。将其更改为:

def combinationOfK(K,L):
    result = []
    if K <= 0:
        result.append([])
        return result
    for i in range(len(L)):
        thisone = L[i:i+1]
        for another in combinationOfK(K-1, L[i+1:]):  # the error
            result.append(thisone + another)
    return result

但是,你为什么反对收益?生成器可以生成可读、高效的代码。Yield关键字Explained这篇文章的重点并不是要放弃它,而是要解释它。在

在您发布的生成器代码中:

^{pr2}$

return语句与return在普通函数中的含义不同。在生成器中,return立即引发StopIteration,这将导致调用者停止对生成器对象的迭代。在

相关问题 更多 >