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

前端 未结 9 1831
盖世英雄少女心
盖世英雄少女心 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: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

提交回复
热议问题