pythonic way to convert variable to list

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

    That is an ok way to do it (don't forget to include tuples).

    However, you may also want to consider if the argument has a __iter__ method or __getitem__ method. (note that strings have __getitem__ instead of __iter__.)

    hasattr(arg, '__iter__') or hasattr(arg, '__getitem__')
    

    This is probably the most general requirement for a list-like type than only checking the type.

提交回复
热议问题