查找列表的最大值/最小值时管理空列表/无效输入 (Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23048944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manage empty list/invalid input when finding max/min value of list (Python)
提问by Jon_Computer
I'm finding max value and min value of a list by using max(list)
and min(list)
in Python. However, I wonder how to manage empty lists.
我正在通过使用max(list)
和min(list)
在 Python 中找到列表的最大值和最小值。但是,我想知道如何管理空列表。
For example if the list is an empty list []
, the program raises 'ValueError: min() arg is an empty sequence'
but I would like to know how to make the program just print 'empty list or invalid input'
instead of just crashing. How to manage those errors?
例如,如果列表是一个空列表[]
,程序会引发,'ValueError: min() arg is an empty sequence'
但我想知道如何让程序只打印'empty list or invalid input'
而不是崩溃。如何管理这些错误?
采纳答案by Qrtn
Catch and handle the exception.
捕获并处理异常。
try:
print(min(l), max(l))
except (ValueError, TypeError):
print('empty list or invalid input')
ValueError
is raised with an empty sequence. TypeError
is raised when the sequence contains unorderable types.
ValueError
用空序列引发。TypeError
当序列包含不可排序的类型时引发。
回答by Alex Riley
In Python 3.4, a default
keyword argument has been added to the min
and max
functions. This allows a value of your choosing to be returned if the functions are used on an empty list (or another iterable object). For example:
在 Python 3.4 中,和函数中default
添加了关键字参数。如果在空列表(或另一个可迭代对象)上使用这些函数,则这允许返回您选择的值。例如:min
max
>>> min([], default='no elements')
'no elements'
>>> max((), default=999)
999
>>> max([1, 7, 3], default=999) # 999 is not returned unless iterable is empty
7
If the default
keyword is not given, a ValueError
is raised instead.
如果default
未给出关键字,ValueError
则会引发a 。
回答by Curtis Yallop
Specifying a default in earlier versions of Python:
在早期版本的 Python 中指定默认值:
max(lst or [0])
max(lst or ['empty list'])