[英]Python Recursive Generator
我正在嘗試制作一個遞歸生成器,但是我顯然缺少了一些東西。 基本上,我有一個直方圖特定尺寸的正值和負值列表,並且想要獲得正值和負值的每種組合。 例如:
input = [[-1,2],[-3,4],[-5,6]]
我需要的結果是(盡管我希望將此作為生成器而不是列表,但是您明白了):
output = [[-1, -3, -5],[-1, -3, 6],[-1, 4, -5],[-1, 4, 6],[2, -3, -5],[2, -3, 6],[2, 4, -5],[2, 4, 6]]
我設法做到這一點,但是只能將其追加到遞歸內的全局列表中,但是我確實希望我可以使用生成器來完成此操作並遍歷我的函數,因為這樣做會使IMO更加整潔。
這是我現在所擁有的:
def combs(idx,array,current=[]):
for item in array[idx]:
current_copy = current[:]
current_copy.append(item)
if idx + 1 < len(array):
combs(idx+1,array,current_copy)
else:
print current_copy
# yield current_copy
這將完全打印出我想要的內容,但是當我嘗試將打印內容更改為產量並循環使用該功能時,它將無法正常工作。 (例如)
for item in combs(0,input,[]):
print item
此任務的另一個選項是itertools.product
函數:
>>> from itertools import product
>>> input = [[-1,2],[-3,4],[-5,6]]
>>> list(product(*input))
[(-1, -3, -5), (-1, -3, 6), (-1, 4, -5), (-1, 4, 6), (2, -3, -5), (2, -3, 6), (2, 4, -5), (2, 4, 6)]
如果您使用的是Python 3.3或更高版本,則需要yield from
語句:
def combs(idx,array,current=[]):
for item in array[idx]:
current_copy = current[:]
current_copy.append(item)
if idx + 1 < len(array):
yield from combs(idx+1,array,current_copy)
else:
yield current_copy
在Python 2.7上,您可以將yield from
擴展為一個循環:
def combs(idx,array,current=[]):
for item in array[idx]:
current_copy = current[:]
current_copy.append(item)
if idx + 1 < len(array):
for i in combs(idx+1,array,current_copy):
yield i
else:
yield current_copy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.