展平混合类型的列表 [英] Flattened out a mixed type of list

查看:93
本文介绍了展平混合类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的混合列表:

I have a mixed list that looked like this:

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

它是使用以下命令创建的:

It was created with this command:

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',这不是我想要的:

I tried this, but it flattened out even the string 'NONRBP' which is not what I want:

 [item for sublist in mixl for item in sublist]

推荐答案

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

这篇关于展平混合类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆