Python filter/max组合检查空i

2024-06-16 10:55:16 发布

您现在位置:Python中文网/ 问答频道 /正文

(使用Python3.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)

有没有更好的办法?

编辑:对不起,这个愚蠢的符号。函数的参数实际上是任意的iterable,而不是list。


Tags: 代码noneanreturnifis原因解决方案
3条回答

也可以使用reduce表达式return reduce(lambda a,b: a<b and a or b,x) or None

def f(lst):
    # if you want the exact same filtering as the original, you could use
    # lst = [item for item in lst if (item is not None and item != 0)]

    lst = [item for item in lst if item]
    if lst: return min(lst)
    else: return None

列表理解只允许不计算为布尔值false的项(它过滤掉0和None)

空列表(即.[]将计算为False),因此“if lst:”将仅在列表具有项时触发

def f(lst):
  flt = filter(lambda x : x is not None and x != 0, lst)
  try:
    return min(flt)
  except ValueError:
    return None

当序列为空时,min抛出ValueError。这遵循了常见的“更容易请求原谅”的模式。

EDIT:基于reduce的解决方案

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)

相关问题 更多 >