How to test if every item in a list of type 'int'?

后端 未结 7 2016
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 16:21

Say I have a list of numbers. How would I do to check that every item in the list is an int?
I have searched around, but haven\'t been able to find anything on this.

7条回答
  •  猫巷女王i
    2020-12-08 16:48

    The following statement should work. It uses the any builtin and a generator expression:

    any(not isinstance(x, int) for x in l)
    

    This will return true if there is a non-int in the list. E.g.:

    >>> any(not isinstance(x, int) for x in [0,12.])
    True
    >>> any(not isinstance(x, int) for x in [0,12])
    False
    

    The all builtin could also accomplish the same task, and some might argue it is makes slightly more sense (see Dragan's answer)

    all(isinstance(x,int) for x in l)
    

提交回复
热议问题