2012-07-10 78 views
0

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

我尝试以下,但它不工作:

newValue = list(retValue) 

显然,我不能这样做,因为list(some int)整数不是迭代。有没有另外一种方法呢?

在此先感谢!

+1

“我有一些代码可能会返回一个int或列表。“**为什么它以这种方式行事**?它是你的代码吗?为什么不把它调整为总是返回相同类型的东西呢?它有一个很好的理由说明它为什么返回一个int(而不是一个带有1个int的列表) ),或者没有... – 2012-07-10 23:00:25

回答

9

定义自己的功能:

def mylist(x): 
    if isinstance(x,(list,tuple)): 
     return x 
    else: 
     return [x] 


>>> mylist(5) 
[5] 
>>> mylist([10]) 
[10] 
+0

铸造[x]的问题是,如果x已经是一个列表,这将使它成为一个嵌套列表,这是不希望的。任何方式来避免这种情况? – turtlesoup 2012-07-10 21:46:00

+0

@Jimster – 2012-07-10 21:48:55

+0

'如果不是isinstance(x,(tuple,list)):return [x]'...也许 – 2012-07-10 21:49:19

2
if isinstance(x,list): return x 
else: return [x] 

就是这样。

当然,这不会对其他迭代类型进行智能处理,但并不清楚你是否想将所有迭代对象看作是列表(也许你会,也许你不会)。

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] 
+1

用于鸭子打字的+1 ...“如果它看起来像一只鸭子,鸭子像鸭子一样,它肯定是一只鸭子。” – RobB 2012-07-10 22:05:21

+0

用于鸭子打字的+1。 – 2012-07-10 23:11:10

+2

用于鸭子打字的+1,_but_,你可以用['isinstance(n,collections.Iterable)']获得与我认为相同的行为(http://docs.python.org/library /collections.html#collections.Iterable)。另外,OP要求列表;为了得到像列表一样的东西,但消除了类似发生器和类字典的东西,['collections.Sequence'](http://docs.python.org/library/collections.html#collections.Sequence)非常方便。 – senderle 2012-07-10 23:40:52

2

尝试将变量转换为int。如果它已经是一个int,这是一个无操作。如果它是一个列表,则会引发TypeError。

try: 
    return [int(x)] 
except TypeError: 
    return x 

尽管如果异常情况发生的概率很高,但通常会使用异常来控制流量。这是因为处理异常是一项相当长的任务。

另一种方法是使用isinstance运算符。

if isinstance(x, list): 
    return x 
else: 
    return [x] 
2
listInt = intVal if isinstance(intVal,list) else [intVal] 

这将始终返回一个列表,如果值不是一个列表。 希望这有助于

+0

+1。 Python三元组使用不足... – dawg 2012-07-11 01:55:26

2

这真的只是Hugh Bothwell的答案的变化,但是...如果你想国家的最先进的鸭打字,你可以得到的hasattr(rval, '__iter__')语义在一个更具吸引力的包isinstance(rval, collections.Iterable)。所以......

def wrap_in_iterable(x): 
    if isinstance(x, collections.Iterable): 
     return x 
    else: 
     return [x] 

另外,也许你想要一个列表,而不仅仅是一个迭代;得到类似列表的东西,但消除了类似发电机和字典的东西,collections.Sequence很方便。因为collections.Sequencecollection.Iterable定义__subclasshook__ s表示执行相应hasattr检查(不要无限发电机传递给这个函数。)

def convert_to_sequence(x): 
    if isinstance(x, collections.Sequence): 
     return x 
    elif isinstance(x, collections.Iterable): 
     return list(x) 
    else 
     return [x] 

这些工作。

最后,冒着无聊的风险 - 如果您对返回函数有控制权,只要可能就返回一个项目列表。