扁平化混合类型的列表

时间:2014-06-26 04:25:35

标签: python list

我有一个混合列表,如下所示:

[('1CFV',), 'NONRBP', [0.00325071141379, 0.278046326931, 0.291350892759]]

它是使用此命令创建的:

In [12]: l1 =  [0.00325071141379, 0.278046326931, 0.291350892759]

In [13]: t1 = ('1CFV',)                                                          

In [14]: s1 = "NONRBP"

In [15]: mixl = [t1,s1,l1]

In [16]: mixl

有没有办法将其转换为:

   ['1CFV', 'NONRBP', 0.00325071141379, 0.278046326931, 0.291350892759]

我尝试了这个,但它甚至弄平了字符串'NONRBP',这不是我想要的:

 [item for sublist in mixl for item in sublist]

2 个答案:

答案 0 :(得分:2)

>>> final = []
>>> a = [('1CFV',), 'NONRBP', [0.00325071141379, 0.278046326931, 0.291350892759]]
>>> for i in a:
...   if hasattr(i, '__iter__'):
...     for j in i:
...       final.append(j)
...   else:
...     final.append(i)
... 
>>> print final
['1CFV', 'NONRBP', 0.00325071141379, 0.27804632693100001, 0.291350892759]

答案 1 :(得分:0)

[item for item in list if type(item) is not list] + 
[item for sublist in mixl if type(item) is list for item in sublist]

解决列表包含列表和其他可迭代项(字符串)的特定情况