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

后端 未结 7 1998
没有蜡笔的小新
没有蜡笔的小新 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条回答
  • 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)
    
    0 讨论(0)
  • 2020-12-08 16:55

    Found myself with the same question but under a different situation: If the "integers" in your list are represented as strings (e.g., as was the case for me after using 'line.split()' on a line of integers and strings while reading in a text file), and you simply want to check if the elements of the list can be represented as integers, you can use:

    all(i.isdigit() for i in myList)
    

    For example:

    >>> myList=['1', '2', '3', '150', '500', '6']
    >>> all(i.isdigit() for i in myList)
    True
    
    >>> myList2=['1.5', '2', '3', '150', '500', '6']
    >>> all(i.isdigit() for i in myList2)
    False
    
    0 讨论(0)
  • 2020-12-08 16:57
    lst = [1,2,3]
    lst2 = [1,2,'3']
    
    list_is_int = lambda lst: [item for item in lst if isinstance(item, int)] == lst
    
    print list_is_int(lst)
    print list_is_int(lst2)
    
    suxmac2:~$ python2.6 xx.py 
    True
    False
    

    ....one possible solution out of many using a list comprehension or filter()

    0 讨论(0)
  • 2020-12-08 16:59
    >>> my_list = [1, 2, 3.25]
    >>> all(isinstance(item, int) for item in my_list)
    False
    
    >>> other_list = range(3)
    >>> all(isinstance(item, int) for item in other_list)
    True
    >>> 
    
    0 讨论(0)
  • 2020-12-08 17:05

    See functions

    def is_int(x):
        if type(x) == int:
            return True
        return
    
    
    def all_int(a):
        for i in a:
            if not is_int(i):
                return False
        return True
    

    Then call

    all_int(my_list) # returns boolean
    
    0 讨论(0)
  • 2020-12-08 17:08
    In [1]: a = [1,2,3]
    
    In [2]: all(type(item)==int for item in a)
    Out[2]: True
    
    0 讨论(0)
提交回复
热议问题