【发布时间】:2011-04-25 19:03:24
【问题描述】:
(使用 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)
有没有更好的方法?
编辑:对不起,愚蠢的符号。函数的参数确实是任意可迭代的,而不是列表。
【问题讨论】:
-
是的。 ActiveState Python 3.1.2。
-
itertools.c_c_c_c_c_COMBO_BREAKER()
标签: python filter iterator python-3.x iterable