(使用Python 3.1)
我知道这个问题已经被问过很多次,用于测试迭代器是否为空的一般问题;显然,对此没有简洁的解决方案(我猜是有原因的 - 迭代器在被要求返回下一个值之前并不真正知道它是否为空)。
不过,我有一个具体的例子,希望我能从中编写出干净且 Python 的代码:
#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)
有更好的方法吗?
编辑:对于愚蠢的符号感到抱歉。函数的参数确实是一个任意的可迭代对象,而不是一个列表。
def f(lst):
flt = filter(lambda x : x is not None and x != 0, lst)
try:
return min(flt)
except ValueError:
return None
min
throws ValueError
当序列为空时。这遵循常见的“更容易请求宽恕”范例。
编辑:无例外的基于归约的解决方案
from functools import reduce
def f(lst):
flt = filter(lambda x : x is not None and x != 0, lst)
m = next(flt, None)
if m is None:
return None
return reduce(min, flt, m)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)