flattening and rebuilding a simple list of lists

Neil Cerutti neilc at norwich.edu
Mon Nov 30 09:06:50 EST 2009


On 2009-11-30, Esmail <ebonak at hotmail.com> wrote:
> 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.

Depending on your usage pattern, directly mutating the original
through a simple "view" might be a viable alternative:

def set_flattened(lst, i, val):
  j = 0
  while i >= len(lst[j]):
    i -= len(lst[j])
    j += 1
  lst[j][i] = val

def get_flattened(lst, i):
  j = 0
  while i >= len(lst[j]):
    i -= len(lst[j])
    j += 1
  return lst[j][i]

A "view" should be easier to use and debug than your current
flatten, mutate and unflatten approach.

The above functions obviously make the maximum number of
assumptions about your data structures, and currently don't work
sensibly with negative indices.

-- 
Neil Cerutti



More information about the Python-list mailing list