flattening and rebuilding a simple list of lists

Peter Otten __peter__ at web.de
Mon Nov 30 08:34:29 EST 2009


Esmail wrote:

> Hi,
> 
> I have a list of lists. The number of sublists may vary. The sizes of
> the sublists may also vary. For instance, here I have a list with 3
> sublists of differing sizes.
> 
>   [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']]
> 
> This list will never be any deeper than this one level.
> 
> What I would like to do is flatten this list, rearrange the items in
> the new flattened list and then recreate the list of sublists with the
> new content. I would like the sublists to have the same size and order
> (relative to each other) as before.
> 
> My code below seems to work, but it feels a bit "hack'ish", and I
> am concerned about efficiency - so I would appreciate suggestions.

I don't think it's hackish, but here's an alternative:

>>> items = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']]
>>> flat = sum(items, [])
>>> flat.reverse()
>>> from itertools import imap, islice
>>> flat = iter(flat)
>>> [list(islice(flat, size)) for size in imap(len, items)]
[['i', 'h', 'g'], ['f', 'e'], ['d', 'c', 'b', 'a']]

Peter



More information about the Python-list mailing list