Check if all elements of a list are of the same type

前端 未结 9 1687
盖世英雄少女心
盖世英雄少女心 2020-11-28 05:08

How can I check if the elements of a list are of the same type, without checking individually every element if possible?

For example, I would like to have a function

相关标签:
9条回答
  • 2020-11-28 05:51

    I prefer to use map for a case like this:

    from types import IntType
    In [21]: map((lambda x: isinstance(x, IntType)), x)
       Out[21]: [True, False, False]
    
    0 讨论(0)
  • 2020-11-28 05:54

    The simplest way to check if a list is composed of omogeneous elements can be with the groupby function of the itertools module:

    from itertools import groupby
    len(list(groupby(yourlist,lambda i:type(i)))) == 1
    

    If th len is different from one it means that it found different kind of types in the list. This has the problem of running trough the entire sequence. If you want a lazy version you can write a function for that:

    def same(iterable):
        iterable = iter(iterable)
        try:
            first = type(next(iterable))
            return all(isinstance(i,first) for i in iterable)
        except StopIteration:
            return True
    

    This function store the type of the first element and stop as soon as it find a different type in one of the elements in the list.

    Both of this methods are strongly sensitive to the type, so it will see as different int and float, but this should be as close as you can get to your request

    EDIT:

    replaced the for cycle with a call to all as suggested by mgilson

    in case of void iterator it returns True to be consistent with the behavior of the bulitin all function

    0 讨论(0)
  • 2020-11-28 05:56

    Using any(), no need to traverse whole list. Just break as soon as object which is not int or long is found:

    >>> not any(not isinstance(y,(int,long)) for y in [1,2,3])
    True
    >>> not any(not isinstance(y,(int,long)) for y in [1,'a',2,3])
    False
    
    0 讨论(0)
提交回复
热议问题