<p>我刚刚意识到这段代码并没有像我希望的那样工作。。。在</p>
<pre><code>for i in [0,2,4]:
if i%2==0:
print i
else:
print "There are no EVEN #s"
</code></pre>
<p>那么,编码这种结构的最佳方式是什么</p>
<p>这样做的目的是,如果“if”语句在“for”循环的所有迭代中都不为真,则运行“else”语句代码</p>
<p>我认为更“pythonic”的方法是过滤列表并检查过滤后的列表是否包含任何元素以确定要打印的内容:</p>
<pre><code>lst = [0, 2, 4]
filtered = [x for x in lst if x%2 == 0]
if filtered:
for item in filtered:
print item
else:
print "No evens"
</code></pre>