max*_*max 5 python iterator iterable filter python-3.x
(使用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)
Run Code Online (Sandbox Code Playgroud)
有什么更好的方法吗?
编辑:抱歉的愚蠢表示法。函数的参数确实是一个任意可迭代的,而不是列表。
小智 8
t = [1,2,3]
if any(filter(lambda x: x == 10, t)):
print("found 10")
Run Code Online (Sandbox Code Playgroud)
def f(lst):
flt = filter(lambda x : x is not None and x != 0, lst)
try:
return min(flt)
except ValueError:
return None
Run Code Online (Sandbox Code Playgroud)
min
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)
Run Code Online (Sandbox Code Playgroud)