30秒学会 Python 片段 · 2022年12月31日

30秒学会 Python 片段 – Cast to list

Casts the provided value as a list if it’s not one.

  • Use isinstance() to check if the given value is enumerable.
  • Return it by using list() or encapsulated in a list accordingly.

代码实现

def cast_list(val):
  return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]

使用样例

cast_list('foo') # ['foo']
cast_list([1]) # [1]
cast_list(('foo', 'bar')) # ['foo', 'bar']

翻译自:https://www.30secondsofcode.org/python/s/cast-list