一个安全的max()函数,用于空列表 [英] A safe max() function for empty lists

查看:109
本文介绍了一个安全的max()函数,用于空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

评估,

max_val = max(a)

将导致错误

ValueError: max() arg is an empty sequence

除了tryexcept捕获以外,还有没有更好的方法来防止此错误?

Is there a better way of safeguarding against this error other than a try, except catch?

a = []
try:
    max_val = max(a)
except ValueError:
    max_val = default 

推荐答案

在Python 3.4+中,您可以使用 default关键字参数:

In Python 3.4+, you can use default keyword argument:

>>> max([], default=99)
99

在较低版本中,您可以使用or:

In lower version, you can use or:

>>> max([] or [99])
99

注意:第二种方法不适用于所有可迭代对象.特别是对于只考虑真值的迭代器.

NOTE: The second approach does not work for all iterables. especially for iterator that yield nothing but considered truth value.

>>> max(iter([]) or 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

这篇关于一个安全的max()函数,用于空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆