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

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

问题描述

评估,

max_val = max(a)

会导致错误,

ValueError: max() arg 是一个空序列

除了 tryexcept catch 之外,还有没有更好的方法来防止这个错误?

a = []尝试:max_val = max(a)除了值错误:max_val = 默认

解决方案

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

<预><代码>>>>最大值([],默认值=99)99

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

<预><代码>>>>最大值([] 或 [99])99

注意:第二种方法不适用于所有可迭代对象.特别是对于那些只产生被认为是真值的迭代器.

<预><代码>>>>max(iter([]) 或 0)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError: max() arg 是一个空序列

Evaluating,

max_val = max(a)

will cause the error,

ValueError: max() arg is an empty sequence

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 

解决方案

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

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

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天全站免登陆