Python: check if an object is a sequence

后端 未结 8 2029
长情又很酷
长情又很酷 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:59

    For Python 3 and 2.6+, you can check if it's a subclass of collections.Sequence:

    >>> import collections
    >>> isinstance(myObject, collections.Sequence)
    True
    

    In Python 3.7 you must use collections.abc.Sequence (collections.Sequence will be removed in Python 3.8):

    >>> import collections.abc
    >>> isinstance(myObject, collections.abc.Sequence)
    True
    

    However, this won't work for duck-typed sequences which implement __len__() and __getitem__() but do not (as they should) subclass collections.Sequence. But it will work for all the built-in Python sequence types: lists, tuples, strings, etc.

    While all sequences are iterables, not all iterables are sequences (for example, sets and dictionaries are iterable but not sequences). Checking hasattr(type(obj), '__iter__') will return True for dictionaries and sets.

    0 讨论(0)
  • 2020-12-05 10:05

    The Python 2.6.5 documentation describes the following sequence types: string, Unicode string, list, tuple, buffer, and xrange.

    def isSequence(obj):
        return type(obj) in [str, unicode, list, tuple, buffer, xrange]
    
    0 讨论(0)
提交回复
热议问题