<p>(使用Python3.1)</p>
<p>我知道这个问题已经被问过很多次了,是为了测试迭代器是否为空的一般问题;显然,没有一个完美的解决方案(我想是有原因的——迭代器在被要求返回下一个值之前并不真正知道它是否为空)。</p>
<p>不过,我有一个具体的例子,我希望我可以用它来编写干净的Pythonic代码:</p>
<pre><code>#lst is an arbitrary iterable
#f must return the smallest non-zero element, or return None if empty
def f(lst):
flt = filter(lambda x : x is not None and x != 0, lst)
if # somehow check that flt is empty
return None
return min(flt)
</code></pre>
<p>有没有更好的办法?</p>
<p>编辑:对不起,这个愚蠢的符号。函数的参数实际上是任意的iterable,而不是list。</p>