(使用 Python 3.1)
我知道对于测试迭代器是否为空的一般问题,这个问题已经被问过很多次了;显然,没有很好的解决方案(我猜是有原因的——迭代器在被要求返回下一个值之前并不知道它是否为空)。
然而,我有一个具体的例子,并希望我可以用它制作干净和 Pythonic 的代码:
#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)
有没有更好的方法来做到这一点?
编辑:对不起愚蠢的符号。函数的参数确实是任意可迭代的,而不是列表。