如何检查一个变量是否为列表,并且列表中所有数据类型均为整数,如果不是,则相应地抛出异常?

2024-04-26 01:11:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这门课(我只是c/p的重要部分):

    x = [1,2,3,4,5, 'hole']

try:
    if type(x) == list:
        print("all ok")
    else:
        raise Exception('Variable is not a list')

except Exception as error:
    print('Caught an error: ' + repr(error))

如您所见,我正在检查变量“file”实际上是一个列表。如果不是,则会引发异常。准确地说,这是一个值错误,但我只是把它推广到例外。你知道吗

不过,我需要更具体一些。我希望我的setter也能检查“file”列表中的元素是否都是整数。你知道吗

有谁能帮我解决这个问题,并提出另一个例外,那就是:“列表中的所有元素都不是整数”。你知道吗

提前谢谢。你知道吗


Tags: 元素列表iftypeexceptionok整数error
3条回答
x = [1,2,3,4,5, 'hole']

try:
    if type(x) == list:
        print("all ok")
        if all(type(element) == int for element in x):
            print("all integers")
        else:
            raise ValueError('all elements inside your list are not integers')
    else:
        raise ValueError('Variable is not a list')

except ValueError as error:
    print('Caught an error: ' + repr(error))

可以使用isinstance检查变量是否属于给定类型,并相应地引发异常。你知道吗

对于无效数据

>>> x = [1,2,3,4,5, 'hole']
>>> if not isinstance(x, list): raise ValueError("Not a list")
...
>>> if any(not isinstance(i,int) for i in x): raise ValueError("List elements are not int")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: List elements are not int

对于有效数据

>>> x=[1,2,3,4,5]
>>> if not isinstance(x, list): raise ValueError("Not a list")
...
>>> if any(not isinstance(i,int) for i in x): raise ValueError("List elements are not int")
...

或者

>>> x = [1,2,3,4,5, 'hole']
>>> try:
...     for n in x:
...         if n==int(n): pass
... except ValueError:
...     raise ValueError("Expected a list of integers")
... except TypeError:
...     raise TypeError("Expected a list")
...
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
ValueError: Expected a list of integers

代码的上一个版本已经根据需要引发了异常。我只想建议您使用除type()和==之外的isinstance函数。你知道吗

try:
    if isinstance(x, list):
        print("all ok")
        if all(isinstance(element, int) for element in x):
            print("all integers")
        else:
            raise ValueError('all elements inside your list are not integers')
    else:
        raise ValueError('Variable is not a list')

except ValueError as error:
    print('Caught an error: ' + repr(error))    

相关问题 更多 >