回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我相信我被嵌套的范围界定规则和列表理解的结合所困扰。<a href="http://www.python.org/~jeremy/weblog/040204.html" rel="noreferrer">Jeremy Hylton's blog post</a>是关于原因的暗示,但我对CPython的实现还不太了解,无法找到解决这个问题的方法。在</p>
<p>这是一个(过于复杂?)例子。如果人们有一个简单的演示它,我想听听。问题是:使用next()的列表理解将填充上一次迭代的结果。在</p>
<p><strong>编辑</strong>:问题:</p>
<p>这到底是怎么回事,我该怎么解决?我必须使用标准for循环吗?显然,函数运行的次数是正确的,但是列表的理解结果是<em>最终的</em>值,而不是每个循环的结果。在</p>
<p>一些假设:</p>
<ul>
<li>发电机?在</li>
<li>懒散地填写清单理解?在</li>
</ul>
<p><strong>编码</strong></p>
<pre><code>import itertools
def digit(n):
digit_list = [ (x,False) for x in xrange(1,n+1)]
digit_list[0] = (1,True)
return itertools.cycle ( digit_list)
</code></pre>
^{pr2}$
<pre><code>class counter(object):
def __init__(self):
self.counter = [ digit(4) for ii in range(2) ]
self.totalcount=0
self.display = [0,] * 2
def next(self):
self.totalcount += 1
self.display[-1] = self.counter[-1].next()[0]
print self.totalcount, self.display
return self.display
def next2(self,*args):
self._cycle(1)
self.totalcount += 1
print self.totalcount, self.display
return self.display
def _cycle(self,digit):
d,first = self.counter[digit].next()
#print digit, d, first
#print self._display
self.display[digit] = d
if first and digit > 0:
self._cycle(digit-1)
C = counter()
[C.next() for x in range(5)]
[C.next2() for x in range(5)]
</code></pre>
<p><strong>输出</strong></p>
<pre>
In [44]: [C.next() for x in range(6)]
1 [0, 1]
2 [0, 2]
3 [0, 3]
4 [0, 4]
5 [0, 1]
6 [0, 2]
Out[44]: [[0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2]]
In [45]: [C.next2() for x in range(6)]
7 [0, 3]
8 [0, 4]
9 [1, 1]
10 [1, 2]
11 [1, 3]
12 [1, 4]
Out[45]: [[1, 4], [1, 4], [1, 4], [1, 4], [1, 4], [1, 4]]
# this should be: [[0,3],[0,4]....[1,4]] or similar
</pre>