如何将int转换为列表?

tur*_*oup 0 python list

我有一些代码可能返回单个int或列表.当它返回一个int时,我需要将它转换为只包含int的列表.

我尝试了以下,但它不起作用:

newValue = list(retValue)
Run Code Online (Sandbox Code Playgroud)

显然我做不到,list(some int)因为整数不可迭代.还有另一种方法吗?

提前致谢!

Ash*_*ary 9

定义自己的功能:

 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)


Hug*_*ell 7

在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)

  • 对于鸭子打字+1,_but_,你可以在[`isinstance(n,collections.Iterable)`]中得到相同的行为(我认为)更漂亮的方式(http://docs.python.org/library/ collections.html#collections.Iterable).此外,OP要求列表; 为了获得类似列表的东西,但是消除类似生成器和类似dict的东西,[`collections.Sequence`](http://docs.python.org/library/collections.html#collections.Sequence)很方便. (2认同)