Check if object is a number or boolean

2020-05-29 12:55发布

Design a logical expression equivalent to the following statement:

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.

What I have:

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?

6条回答
仙女界的扛把子
2楼-- · 2020-05-29 13:29

To answer the specific question:

isinstance(x[0], (int, float))

This checks if x[0] is an instance of any of the types in the tuple (int, float).

You can add bool in there, too, but it's not necessary, because bool is itself a subclass of int.

Doc reference:


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'
查看更多
家丑人穷心不美
3楼-- · 2020-05-29 13:33

You should compare the type of x to the bool class:

type(x) == bool

or:

type(x) == type(True)

Here is more on the type method

From Data model docs:

Booleans (bool)

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

查看更多
贼婆χ
4楼-- · 2020-05-29 13:34

In python3 this would be: type(x)==bool see example.

查看更多
放我归山
5楼-- · 2020-05-29 13:41
import types
type(x) == types.BooleanType
查看更多
成全新的幸福
6楼-- · 2020-05-29 13:44

I follow the recent answer who tell to use type and it seems to be the incorrect way according to pylint validation:

I got the message:

C0123: Using type() instead of isinstance() for a typecheck. (unidiomatic-typecheck)

Even if it's an old answer, the correct one is the accepted answer of @Lev Levitsky:

isinstance(x[0], (int, float))
查看更多
你好瞎i
7楼-- · 2020-05-29 13:49

Easiest i would say:

type(x) == type(True)
查看更多
登录 后发表回答