pythonic way to convert variable to list

前端 未结 8 494
时光说笑
时光说笑 2020-12-24 03:14

I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the

相关标签:
8条回答
  • 2020-12-24 03:52

    I like Andrei Vajna's suggestion of hasattr(var,'__iter__'). Note these results from some typical Python types:

    >>> hasattr("abc","__iter__")
    False
    >>> hasattr((0,),"__iter__")
    True
    >>> hasattr({},"__iter__")
    True
    >>> hasattr(set(),"__iter__")
    True
    

    This has the added advantage of treating a string as a non-iterable - strings are a grey area, as sometimes you want to treat them as an element, other times as a sequence of characters.

    Note that in Python 3 the str type does have the __iter__ attribute and this does not work:

    >>> hasattr("abc", "__iter__")
    True
    
    0 讨论(0)
  • 2020-12-24 03:53

    This seems like a reasonable way to do it. You're wanting to test if the element is a list, and this accomplishes that directly. It gets more complicated if you want to support other 'list-like' data types, too, for example:

    isinstance(input, (list, tuple))
    

    or more generally, abstract away the question:

    def iterable(obj):
      try:
        len(obj)
        return True
      except TypeError:
        return False
    

    but again, in summary, your method is simple and correct, which sounds good to me!

    0 讨论(0)
提交回复
热议问题