Test type of elements python tuple/list

前端 未结 4 1596

How do you verify that the type of all elements in a list or a tuple are the same and of a certain type?

for example:

(1, 2, 3)  # test for all int          


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 05:26

    all(isinstance(n, int) for n in lst)
    

    Demo:

    In [3]: lst = (1,2,3)
    
    In [4]: all(isinstance(n, int) for n in lst)
    Out[4]: True
    
    In [5]: lst = (1,2,'3')
    
    In [6]: all(isinstance(n, int) for n in lst)
    Out[6]: False
    

    Instead of isinstance(n, int) you could also use type(n) is int

提交回复
热议问题