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

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

    One approach would not be to test, but to insist. This means your program can handle a broader range of inputs intelligently -- it won't fail if someone passes it a float instead.

    int_list = [int(x) for x in int_list]
    

    or (in-place):

    for i, n in enumerate(int_list):
        int_list[i] = int(n)
    

    If something can't be converted, it will throw an exception, which you can then catch if you care to.

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