我有一些代码可能返回单个int或列表.当它返回一个int时,我需要将它转换为只包含int的列表.
我尝试了以下,但它不起作用:
newValue = list(retValue)
Run Code Online (Sandbox Code Playgroud)
显然我做不到,list(some int)因为整数不可迭代.还有另一种方法吗?
提前致谢!
定义自己的功能:
def mylist(x):
if isinstance(x,(list,tuple)):
return x
else:
return [x]
>>> mylist(5)
[5]
>>> mylist([10])
[10]
Run Code Online (Sandbox Code Playgroud)
在Python中,鸭子打字是可取的 - 不要测试特定类型,只测试它是否支持你需要的方法("我不在乎它是否是鸭子,只要它嘎嘎叫").
def make_list(n):
if hasattr(n, '__iter__'):
return n
else:
return [n]
a = make_list([1,2,3]) # => [1,2,3]
b = make_list(4) # => [4]
Run Code Online (Sandbox Code Playgroud)