Python itertools - 组合逻辑 [英] Python itertools - combination logic
本文介绍了Python itertools - 组合逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试理解itertools中的组合函数,但我坚持使用其中一个循环。除了else语句之外,我无法理解正在发生的事情。做indices [i] + = 1,for循环落入返回函数?
另外,为什么代码需要规定j + 1 = j-1 + 1?
def 组合(iterable,r):
# 组合('ABCD',2) - > AB AC AD BC BD CD
# 组合(范围(4),3) - > 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r> n:
print ( oops)
indices = list(range(r))
yield tuple(pool [i] for i in indices)
while True :
for i in reverse(range(r) )):
如果 indices [i]!= i + n - r:
break
else :
return
indices [i] + = 1
j range(i + 1 ,r):
indices [j] = indices [j- 1 ] + 1
yield tuple(pool [i] for i in indices)
我尝试了什么:
我理解返回和其他声明整体,我直到这一点,我已经完成了代码。我只是在这里寻求帮助。
解决方案
可以在 Python yield关键字解释了| Python技巧 [ ^ ]。
I'm trying to understand the combination function in itertools, but I'm stuck with one of the loops. Beyond the else statement, I can't follow what's going on. Do the "indices[i] += 1", and for loop fall into the return function?
Also, why does the code need to stipulate the j + 1 = j-1+1?
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
print("oops")
indices = list(range(r))
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
What I have tried:
I understand return and else statements overall, and I've worked through the code up until this point. I'm just looking for some help here.
解决方案
A good explanation can be found at The Python yield keyword explained | Python Tips[^].
这篇关于Python itertools - 组合逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文