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

后端 未结 7 2004
没有蜡笔的小新
没有蜡笔的小新 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: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
    

提交回复
热议问题