查找列表的最大值/最小值时管理空列表/无效输入 (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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:11:21  来源:igfitidea点击:

Manage empty list/invalid input when finding max/min value of list (Python)

pythonlisterror-handlingmaxmin

提问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')

ValueErroris raised with an empty sequence. TypeErroris raised when the sequence contains unorderable types.

ValueError用空序列引发。TypeError当序列包含不可排序的类型时引发。

回答by Alex Riley

In Python 3.4, a defaultkeyword argument has been added to the minand maxfunctions. 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添加了关键字参数。如果在空列表(或另一个可迭代对象)上使用这些函数,则这允许返回您选择的值。例如:minmax

>>> 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 defaultkeyword is not given, a ValueErroris 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'])