<p>在重复同一个列表时,您正在从列表中删除条目。您可以简单地使用列表理解来保留所需的元素:</p>
<pre><code>products = [product for product in products
if product.get('Product', None) not in blacklist]
</code></pre>
<p>或使用<code>filter</code>:</p>
<pre><code>products = filter(lambda product: product.get('Product', None) not in blacklist, products)
</code></pre>
<hr/>
<p><strong>关于从<code>a = [1, 2, 3, 4, 5, 6, 7, 8]</code>删除的更新:</strong></p>
<p>你说以下代码有效:</p>
<pre><code>a = [1, 2, 3, 4, 5, 6, 7, 8]
for e in a:
if e % 2 = 0:
a.remove(e)
print(a) # [1, 3, 5, 7]
</code></pre>
<p>好吧,它不起作用,但它只是一个幻觉,让我们添加一些打印语句来理解:</p>
<pre><code>for e in a:
print 'Next Item: ', e
if e % 2 = 0:
a.remove(e)
print 'Current List: ', a
</code></pre>
<p>下面是<code>print</code>语句的输出:</p>
<pre><code>Next Item: 1
Current List: [1, 2, 3, 4, 5, 6, 7, 8]
Next Item: 2
Current List: [1, 3, 4, 5, 6, 7, 8]
Next Item: 4
Current List: [1, 3, 5, 6, 7, 8]
Next Item: 6
Current List: [1, 3, 5, 7, 8]
Next Item: 8
Current List: [1, 3, 5, 7]
</code></pre>
<p>如您所见,就在第3次迭代之前,<code>a</code>被更新,<code>3</code>被移到第2个位置,并且由于第2个位置已经被迭代,<code>3</code>从未进入循环。同样,对于其他循环,循环不会运行8次,而只运行5次。你知道吗</p>
<p>如果更改<code>a</code>中值的顺序,将不会得到相同的行为:</p>
<pre><code>a = [1, 4, 2, 3, 6, 8, 7, 5]
</code></pre>
<p>现在,再次运行上面的`for循环:</p>
<pre><code>Next Item: 1
Current List: [1, 4, 2, 3, 6, 8, 7, 5]
Next Item: 4
Current List: [1, 2, 3, 6, 8, 7, 5]
Next Item: 3
Current List: [1, 2, 3, 6, 8, 7, 5]
Next Item: 6
Current List: [1, 2, 3, 8, 7, 5]
Next Item: 7
Current List: [1, 2, 3, 8, 7, 5]
Next Item: 5
Current List: [1, 2, 3, 8, 7, 5]
</code></pre>
<p>所以在列表的末尾,<code>a</code>的值是<code>[1, 2, 3, 8, 7, 5]</code>。你知道吗</p>
<p>就像我之前说的:<em>它不起作用,但它只是一个幻觉,它起作用了</em></p>