查找列表的最大/最小值时,管理空列表/无效输入(Python) [英] Manage empty list/invalid input when finding max/min value of list (Python)
问题描述
我正在使用Python中的max(list)
和min(list)
查找列表的最大值和最小值.但是,我想知道如何管理空列表.
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.
例如,如果列表为空列表[]
,则程序会引发'ValueError: min() arg is an empty sequence'
,但是我想知道如何使程序仅打印'empty list or invalid input'
而不是崩溃.如何处理这些错误?
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?
推荐答案
捕获并处理异常.
try:
print(min(l), max(l))
except (ValueError, TypeError):
print('empty list or invalid input')
ValueError
以空序列引发.当序列包含不可排序的类型时,会引发TypeError
.
ValueError
is raised with an empty sequence. TypeError
is raised when the sequence contains unorderable types.
这篇关于查找列表的最大/最小值时,管理空列表/无效输入(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!