问题描述
设计一个等价于以下语句的逻辑表达式:
x
是三个或五个元素的列表,其中的第二个元素是字符串 'Hip'
并且第一个不是数字或布尔值.
x
is a list of three or five elements, the second element of which is the string 'Hip'
and the first of which is not a number or Boolean.
我有什么:
x = ['Head', 'Hip', 10]
print x[1] is 'Hip'
我的问题:你如何检查它是布尔值还是数字?
My question: How do you check for whether or not it is a Boolean or a number?
推荐答案
回答具体问题:
isinstance(x[0], (int, float))
这将检查 x[0]
是否是元组 (int, float)
中任何类型的实例.
This checks if x[0]
is an instance of any of the types in the tuple (int, float)
.
您也可以在其中添加 bool
,但这不是必需的,因为 bool
本身就是 int
的子类.
You can add bool
in there, too, but it's not necessary, because bool
is itself a subclass of int
.
文档参考:
要评论您当前的代码,您不应该依赖短字符串的实习.您应该使用 ==
运算符比较字符串:
To comment on your current code, you shouldn't rely on interning of short strings. You are supposed to compare strings with the ==
operator:
x[1] == 'Hip'
这篇关于检查对象是数字还是布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!