<p>迭代时对象会被修改;使用<code>for</code>时打印中间结果,打印列表时打印最终结果。你知道吗</p>
<p>如果先将结果附加到列表中,则会再次得到与<code>list()</code>输出相同的结果:</p>
<pre><code>>>> n = neighbours([2], [1,4,5])
>>> res = []
>>> for i in n:
... print(i)
... res.append(i)
...
(deque([2, 1]), deque([4, 5]))
(deque([2, 4]), deque([5, 1]))
(deque([2, 5]), deque([1, 4]))
>>> res
[(deque([2]), deque([1, 4, 5])), (deque([2]), deque([1, 4, 5])), (deque([2]), deque([1, 4, 5]))]
</code></pre>
<p><code>res</code>中的每个元素都是一个元组,具有两个相同的deque对象:</p>
<pre><code>>>> res[0][0] is res[1][0] is res[2][0]
True
>>> res[0][1] is res[1][1] is res[2][1]
True
</code></pre>
<p>您可以生成每个<code>deque</code>的<code>list()</code>副本,从而创建<em>新的</em>对象:</p>
<pre><code>>>> def neighbours(comp0, cand0):
... comp = deque([i for i in comp0])
... cand = deque([i for i in cand0])
... for i in range(len(cand)):
... elem = cand.popleft()
... comp.append(elem)
... yield list(comp), list(cand)
... comp.pop()
... cand.append(elem)
...
>>> n = neighbours([2], [1,4,5])
>>> res = []
>>> for i in n:
... print(i)
... res.append(i)
...
([2, 1], [4, 5])
([2, 4], [5, 1])
([2, 5], [1, 4])
>>> res
[([2, 1], [4, 5]), ([2, 4], [5, 1]), ([2, 5], [1, 4])]
</code></pre>