我有一个列表,其中包含许多列表。我唯一的问题是,我想不断地联合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.]] 提前谢谢你!
发布于 2014-05-10 21:58:08
请尝试以下操作
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']]发布于 2014-05-10 22:23:34
这将匹配您想要的输出,但我不能完全确定匹配的一般条件是什么。
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,输出的配方和示例可能会很有用
https://stackoverflow.com/questions/23581753
复制相似问题