Python: check if an object is a sequence

后端 未结 8 2035
长情又很酷
长情又很酷 2020-12-05 09:17

In python is there an easy way to tell if something is not a sequence? I tried to just do: if x is not sequence but python did not like that

8条回答
  •  死守一世寂寞
    2020-12-05 09:51

    For the sake of completeness. There is a utility is_sequence in numpy library ("The fundamental package for scientific computing with Python").

    >>> from numpy.distutils.misc_util import is_sequence
    >>> is_sequence((2,3,4))
    True
    >>> is_sequence(45.9)
    False
    

    But it accepts sets as sequences and rejects strings

    >>> is_sequence(set((1,2)))
    True
    >>> is_sequence("abc")
    False
    

    The code looks a bit like @adrian 's (See numpy git code), which is kind of shaky.

    def is_sequence(seq):
        if is_string(seq):
            return False
        try:
            len(seq)
        except Exception:
            return False
        return True
    

提交回复
热议问题