pythonic way to convert variable to list

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

    First, there is no general method that could tell a "single element" from "list of elements" since by definition list can be an element of another list.

    I would say you need to define what kinds of data you might have, so that you might have:

    • any descendant of list against anything else
      • Test with isinstance(input, list) (so your example is correct)
    • any sequence type except strings (basestring in Python 2.x, str in Python 3.x)
      • Use sequence metaclass: isinstance(myvar, collections.Sequence) and not isinstance(myvar, str)
    • some sequence type against known cases, like int, str, MyClass
      • Test with isinstance(input, (int, str, MyClass))
    • any iterable except strings:
      • Test with

    .

        try: 
            input = iter(input) if not isinstance(input, str) else [input]
        except TypeError:
            input = [input]
    

提交回复
热议问题