这个问题与我的问题很接近,但并非完全相同:在Python中使用无列出最小值?。我需要考虑列表中所有值均为无的可能性。
我有一种情况,我必须在数据库中查找一些数字,它们可能存在或返回为空。我需要找到这些现有数量的最小值。例如:
min_if_exists(1, 2) returns 1
min_if_exists(5, None) returns 5
min_if_exists(None, None) returns None
幸运的是,我可以做这样的事情:
def min_if_exists(a, b):
return min(a, b)
elif a:
return a
elif b:
return b
else:
return None
以下是上面提到的问题的答案:
lowest = min(x for x in (a, b) if x is not None)
但是,如果a和b为None,我将得到一个异常,因为我输入了一个空序列。我可以简单地捕获异常,也可以在序列中包含任意大的数字(a,b,100000000)。对于可能都是None的任意长数字序列,我可以(大概)用非Python方式做到这一点:
def min_if_exists(list_of_nums):
not_a_none_exists = False
for n in list_of_nums:
if n is not None:
not_a_none_exists = True
if not_a_none_exists:
return min(x for x in list_of_nums if x is not None)
else:
return None
有没有更Pythonic,更简洁的方式来做到这一点?
试试这个,这是一个pythonic解决方案:
def min_if_exists(list_of_nums):
try:
return min(x for x in list_of_nums if x is not None)
except ValueError:
return None
请记住:在Python中,寻求宽容比获得许可容易!引用文档:
这种通用的Python编码风格假定有效键或属性的存在,并在假定被证明为假的情况下捕获异常。这种干净快捷的样式的特征是存在许多try和except语句。该技术与C等其他许多语言通用的LBYL(飞跃前先看)风格形成对比。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句