如何在大型列表中统一特定数量的列表?

时间:2014-05-10 13:40:09

标签: python list

我有一个包含许多列表的列表。只有我的问题是我想要连续统一3个列表,以便我拥有的一个列表变成一个列表,其中包含许多包含联合3个列表的子列表。有人可以帮帮我吗?

我会给出一段输出,让你知道它的样子:

[['303416'], ['ESTs'], [], ['303426'], ['proline', 'and', 'serine', 'rich', '2'], [], ['303438'], ['thymosin,', 'beta', '4,', 'X', 'chromosome'], [], ['303445'], ['zinc', 'finger', 'and', 'BTB', 'domain', 'containing', '16'], [], ['303483'], ['T-box', 'brain', 'gene', '1'], [], ['303562'], ['ESTs'], [], ['303581'], ['ESTs'], [], ['303612'], ['ESTs'], [], ['303720'], ['N-deacetylase/N-sulfotransferase', '(heparan', 'glucosaminyl)', '1'], [], ['303783'], ['coiled-coil', 'domain', 'containing', '50'], [], ['303910'], ['myocyte', 'enhancer', 'factor', '2C'], [], ['313060'], ['DnaJ', '(Hsp40)', 'homolog,', 'subfamily', 'C,', 'member', '5'], [] etc...]

现在我想要一个如下所示的列表:

[ [ '303416', 'ESTs' ] ['303426', 'proline and serine rich 2' ] [ etc.]] 

提前谢谢!

2 个答案:

答案 0 :(得分:0)

尝试以下

In [1]: nested = [['303416'], ['ESTs'], [], ['303426'], ['proline', 'and', 'serine', 'rich', '2'], []]

In [2]: nested_tuples = zip(nested[0::3], nested[1::3], nested[2::3])

In [3]: [list(a + b + c) for a, b, c in nested_tuples]
Out[3]: [['303416', 'ESTs'], ['303426', 'proline', 'and', 'serine', 'rich', '2']]

答案 1 :(得分:0)

这将匹配您想要的输出,但我不完全确定匹配的一般意义上的条件。

def grouper(n, iterable):
    args = [iter(iterable)] * n
    return zip(*args)
g= grouper(2,[x for x in l if x])
list_groups=[]
for i in g:
    list_groups.append([x for x in i[0]]+[y for y in i[1]])
list_groups
[['303416', 'ESTs'], ['303426', 'proline', 'and', 'serine', 'rich', '2'], ['303438', 'thymosin,', 'beta', '4,', 'X', 'chromosome'],....

您应该查看itertools,输出的配方和示例可能很有用