Converting a list of lists to a single list

Zero Piraeus schesis at gmail.com
Tue Jul 23 18:49:19 EDT 2013


:

On 23 July 2013 17:52,  <steve at divillo.com> wrote:
>
> Say I have three lists:
>
> [[A0,A1,A2], [B0,B1,B2] [C0,C1,C2]]
>
> I would like to convert those to a single list that looks like this:
>
[A0,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2,A1,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2,A2,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2]

How's this:

from itertools import chain

def treeify(seq):
    if seq:
        return list(chain(*([x] + treeify(seq[1:]) for x in seq[0])))
    else:
        return []

>>> treeify([['A0', 'A1', 'A2'], ['B0', 'B1', 'B2'], ['C0', 'C1', 'C2']])
['A0', 'B0', 'C0', 'C1', 'C2', 'B1', 'C0', 'C1', 'C2', 'B2', 'C0', 'C1', 'C2',
 'A1', 'B0', 'C0', 'C1', 'C2', 'B1', 'C0', 'C1', 'C2', 'B2', 'C0', 'C1', 'C2',
 'A2', 'B0', 'C0', 'C1', 'C2', 'B1', 'C0', 'C1', 'C2', 'B2', 'C0', 'C1', 'C2']

 -[]z.



More information about the Python-list mailing list