查找列表的最大/最小值时管理空列表/无效输入(Python)

时间:2022-09-28 14:25:03

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.

我在Python中使用max(list)和min(list)找到列表的最大值和最小值。但是,我想知道如何管理空列表。

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是一个空序列'但我想知道如何使程序只打印'空列表或无效输入'而不是只是崩溃。如何管理这些错误?

3 个解决方案

#1


8  

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。

#2


55  

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中,最小和最大函数添加了一个默认关键字参数。如果函数用于空列表(或其他可迭代对象),则允许返回您选择的值。例如:

>>> 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。

#3


43  

Specifying a default in earlier versions of Python:

在早期版本的Python中指定默认值:

max(lst or [0])
max(lst or ['empty list'])

#1


8  

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。

#2


55  

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中,最小和最大函数添加了一个默认关键字参数。如果函数用于空列表(或其他可迭代对象),则允许返回您选择的值。例如:

>>> 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。

#3


43  

Specifying a default in earlier versions of Python:

在早期版本的Python中指定默认值:

max(lst or [0])
max(lst or ['empty list'])