Test type of elements python tuple/list

前端 未结 4 1578

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条回答
  •  Happy的楠姐
    2020-12-05 05:32

    Depending on what you're doing it may be more Pythonic to use duck typing. That way, things that are int-like (floats, etc.) can be passed as well as ints. In this case, you might try converting each item in the tuple to an int, and then catch any exceptions that arise:

    >>> def convert_tuple(t, default=(0, 1, 2)):
    ...     try:
    ...         return tuple(int(x) for x in t)
    ...     except ValueError, TypeError:
    ...         return default
    ... 
    

    Then you can use it like so:

    >>> convert_tuple((1.1, 2.2, 3.3))
    (1, 2, 3)
    >>> convert_tuple((1.1, 2.2, 'f'))
    (0, 1, 2)
    >>> convert_tuple((1.1, 2.2, 'f'), default=(8, 9, 10))
    (8, 9, 10)
    

提交回复
热议问题