【发布时间】:2026-02-13 20:45:02
【问题描述】:
简而言之。除了这个,我怎么写: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 的作用。但我试图编写代码而不 yield 声明。 带有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, yield-keyword-explained 给了我可以替换 yield 的想法。他们给的收据对我不起作用,是:
当你看到一个带有
yield语句的函数时,应用这个简单的 了解会发生什么的技巧:
- 在函数开头插入一行
result = []。- 将每个
yield expr替换为result.append(expr)。- 在函数底部插入一行
return result。- 是的 - 不再有
yield声明!阅读并找出代码。- 将函数恢复为原始定义。
使用它来获取代码而无需 yield 给我这个。代码不工作(函数不可迭代)。 我必须写什么才能让这段代码在没有 yield 的情况下工作?
def combinationOfK(K,L):
result = []
if K <= 0:
result.append([])
return
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
我正在使用这段代码来测试功能,
the_list = ['a','b','c','d','e']
print list(combinationOfK(2, the_list))
引发错误TypeError: 'NoneType' object is not iterable。
【问题讨论】:
-
您忘记在上一个函数中缩进第 5 行。