how to tell a variable is iterable but not a string

后端 未结 8 2148
小蘑菇
小蘑菇 2020-12-02 09:23

I have a function that take an argument which can be either a single item or a double item:

def iterable(arg)
    if #arg is an iterable:
        print \"yes         


        
8条回答
  •  攒了一身酷
    2020-12-02 10:22

    As of 2017, here is a portable solution that works with all versions of Python:

    #!/usr/bin/env python
    import collections
    import six
    
    
    def iterable(arg):
        return (
            isinstance(arg, collections.Iterable) 
            and not isinstance(arg, six.string_types)
        )
    
    
    # non-string iterables    
    assert iterable(("f", "f"))    # tuple
    assert iterable(["f", "f"])    # list
    assert iterable(iter("ff"))    # iterator
    assert iterable(range(44))     # generator
    assert iterable(b"ff")         # bytes (Python 2 calls this a string)
    
    # strings or non-iterables
    assert not iterable(u"ff")     # string
    assert not iterable(44)        # integer
    assert not iterable(iterable)  # function
    

提交回复
热议问题