Python - 如何引发列表中多个项的值错误
如果我有一个项目列表,最终会变成一个二进制数字,那么我该怎么让程序在列表长度超过8个数字,并且里面有不是1或0的数字时,给出一个值错误(或者类似的提示)呢?
比如说这个列表 [1,0,2,0,1,0,0,0,1]。这个列表应该提示错误,说明里面有不是1或0的数字,而且数量超过了8个。
3 个回答
0
你可以这样做:
def typeoferror(mybytes):
return [
len(mybytes) != 8,
any(True for i in mybytes if i not in [0,1])
]
然后可以用它来做测试:
if typeoferror(mybytes)[0] and typeoferror(mybytes)[1]:
raise ValueError('Is not 8-items long and has elements other than 0 or 1')
elif typeoferror(mybytes)[0]:
raise ValueError('Is not 8-items long')
elif typeoferror(mybytes)[1]:
raise ValueError('Has elements other than 0 or 1')
这是同样的代码在运行中的样子:http://codepad.org/tih9ewKq
当然,你可以把typeoferror()
这个函数的结果缓存起来,这样可以提高性能。
这就是你想要的内容吗?
编辑:
根据agf的建议,解决方案变得更高效了。
1
if len(my_list) > 8 or any((x is not 0) and (x is not 1) for x in my_list):
raise ValueError
这个方法不会生成任何中间列表,并且在遇到第一个不好的数字时就会停止(同时也适用于少于八位数的数字)。
如果你想要接受像 True
代表 1
或者 False
代表 0
这样的值,
if len(my_list) > 8 or any(x in (0, 1) for x in my_list):
raise ValueError
它的工作方式是一样的。
1
这样做就可以了。至于结果是否足够干净,完全取决于你自己的要求:
if len(l1) != 8 or len([n for n in l1 if n not in (1, 0)]) != 0:
raise ValueError('Invalid entries or incorrect length')