MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: de-nesting complex nested lists

  • To: mathgroup at smc.vnet.net
  • Subject: [mg111268] Re: de-nesting complex nested lists
  • From: David Bailey <dave at removedbailey.co.uk>
  • Date: Sun, 25 Jul 2010 07:46:42 -0400 (EDT)
  • References: <i2gjui$am$1@smc.vnet.net>

On 25/07/10 07:00, Michael Stern wrote:
> If one has an irregularly nested list like
>
> {{1, 2, 3}, {1, 2,  4}, {{1, 2, 3, 4}, {1, 2, 3, 8}}, {{1, 2, 9}, {{1, 2, 13}, {4, 5, 6}}}},
>
> How might one most easily transform this into a list of uniform Depth 2  ( {{1,2,3},{1,2,4},{1,2,3,4},{1,2,3,8},{1,2,9},{1,2,13},{4,5,6}} ) ?
>
> Thanks in advance,
>
> Michael
>

I am sure there are other more elegant ways to do this, but transforming 
the inner lists to use a different head lets you flatten the rest of the 
structure without touching the lists of integers. You would need a 
different test instead of using Depth if your lists are compound objects 
rather than numbers.

In[3]:= xxx = {{1, 2, 3}, {1, 2,
    4}, {{1, 2, 3, 4}, {1, 2, 3, 8}}, {{1, 2,
     9}, {{1, 2, 13}, {4, 5, 6}}}}

Out[3]= {{1, 2, 3}, {1, 2,
   4}, {{1, 2, 3, 4}, {1, 2, 3, 8}}, {{1, 2,
    9}, {{1, 2, 13}, {4, 5, 6}}}}

step1 = xxx /. (x_List /; Depth[x] == 2) :> g @@ x

Out[6]= {g[1, 2, 3],
  g[1, 2, 4], {g[1, 2, 3, 4],
   g[1, 2, 3, 8]}, {g[1, 2, 9], {g[1, 2, 13], g[4, 5, 6]}}}

Flatten[step1] /. g -> List

Out[8]= {{1, 2, 3}, {1, 2, 4}, {1, 2, 3, 4}, {1, 2, 3, 8}, {1, 2,
   9}, {1, 2, 13}, {4, 5, 6}}

I find it often helps to avoid creating structures like your original 
input by using some structures - f[.......] rather than making 
everything a list.

David Bailey

http://www.dbaileyconsultancy.co.uk


  • Prev by Date: Re: mathematica gives strange result
  • Next by Date: Re: de-nesting complex nested lists
  • Previous by thread: Re: de-nesting complex nested lists
  • Next by thread: Re: de-nesting complex nested lists