pythonic way to convert variable to list

前端 未结 8 523
时光说笑
时光说笑 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
    

提交回复
热议问题