Check if object is a number or boolean

后端 未结 7 1043
攒了一身酷
攒了一身酷 2021-02-06 20:42

Design a logical expression equivalent to the following statement:

x is a list of three or five elements, the second element of which is

相关标签:
7条回答
  • 2021-02-06 21:12

    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:

    • isinstance()
    • built-in numeric types

    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'
    
    0 讨论(0)
  • 2021-02-06 21:15

    Python 2

    import types
    
    x = False
    print(type(x) == types.BooleanType) # True
    

    Python 3

    # No need to import types module
    x = False
    print(type(x) == bool) # True
    
    0 讨论(0)
  • 2021-02-06 21:17

    I like to keep it simple to read.. This will accept bool, string, number and read it to a bool

    def var2bool(v):
    if type(v) == type(True):
        res = v
    elif type(v) == type(0):
        if v == 0:
            res = False
        else:
            res = True
    elif v.lower() in ("yes", "true", "t", "1"):
        res = True
    else:
        res = False
    return res
    
    0 讨论(0)
  • 2021-02-06 21:26

    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))
    
    0 讨论(0)
  • 2021-02-06 21:29

    Easiest i would say:

    type(x) == type(True)
    
    0 讨论(0)
  • 2021-02-06 21:35

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

    0 讨论(0)
提交回复
热议问题