我试图为类似的事情编写一个迭代器(从原始问题中简化):
import numpy as np
class IterableNumber:
def __init__(self, digits):
self.digits = digits
self.zero_indices = np.where(digits == 0)[0]
def __iter__(self):
return self
def next(self):
# For each index in self.zero_indices, loop 1 through 9?
pass
# Other methods omittedIterableNumber接受一个数字数组,但是'0‘是一张不确定的卡片。当我遍历这个对象时,我希望每一个'0‘位数在1到9的范围内循环,即
num = IterableNumber(np.array([5, 5, 0, 5, 0]))
for digits in num:
print digits应打印
[5, 5, 1, 5, 1]
[5, 5, 1, 5, 2]
...
[5, 5, 1, 5, 9]
[5, 5, 2, 5, 1]
[5, 5, 2, 5, 2]
...
...
[5, 5, 9, 5, 9]为一般情况编写此迭代器似乎需要递归,以便处理嵌套循环的可变数量(每个0次有一个循环),就像这个站点上的其他线程所建议的那样。但是如何在迭代器的next()函数的上下文中编写这样的递归函数呢?或者还有别的办法来解决这个问题?如有任何见解,将不胜感激:)
如果与python2.7.3相关,我将使用python 2.7.3。
发布于 2013-12-07 12:41:35
您可以为此使用itertools.product:
import numpy as np
from itertools import product
class IterableNumber:
def __init__(self, digits):
self.digits = digits
self.zero_indices = np.where(self.digits==0)[0]
self.length = len(self.zero_indices)
def __iter__(self):
for x in product(range(10), repeat=self.length):
self.digits[self.zero_indices] = np.array(x)
yield self.digits演示:
>>> for x in IterableNumber(np.array([5, 5, 0, 5, 0])):
print x
...
[5 5 0 5 0]
[5 5 0 5 1]
[5 5 0 5 2]
[5 5 0 5 3]
[5 5 0 5 4]
[5 5 0 5 5]
[5 5 0 5 6]
[5 5 0 5 7]
[5 5 0 5 8]
[5 5 0 5 9]
...
...
[5 5 9 5 3]
[5 5 9 5 4]
[5 5 9 5 5]
[5 5 9 5 6]
[5 5 9 5 7]
[5 5 9 5 8]
[5 5 9 5 9]
>>> https://stackoverflow.com/questions/20441224
复制相似问题