查找列表的最大/最小值时,管理空列表/无效输入(Python) [英] Manage empty list/invalid input when finding max/min value of list (Python)

查看:103
本文介绍了查找列表的最大/最小值时,管理空列表/无效输入(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆