Maison >développement back-end >Tutoriel Python >Python:为什么下面这段程序只删除1个0?
s=[0,0,5,3]
for x in s:
if x==0
s.remove(x)
结果为什么是[0,5,3]而不是[5,3]呢?
<code class="language-python"><span class="k">print</span> <span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">s</span> <span class="k">if</span> <span class="n">x</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">]</span>
</code>
循环时尽量不要对list进行增,删操作
不要在循环中对数组进行变更操作,重要的事情我也不愿意说三次了。
洛克正解,不过手痒,也来分享一下我的看法吧<code class="language-python"><span class="c">#!/usr/bin/env python3</span>
<span class="k">def</span> <span class="nf">check_number</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">False</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">True</span>
<span class="n">s</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="nb">filter</span><span class="p">(</span><span class="n">check_number</span><span class="p">,</span><span class="n">s</span><span class="p">))</span>
</code>
<code class="language-python"><span class="n">s</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="nb">filter</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">s</span><span class="p">))</span>
</code>
s = [i for i in s if i != 0]
#手机码字,对付看吧