5

I have a list in which the first index is mostly increasing, but dips sometimes.

I need to split this list in two or more lists in this way: when the first element of a pair is smaller than the preceding first element, I need to split the list and create new separate lists.

This is an explanatory example:

list = {{1, 10}, {2, 20}, {3, 30}, {4, 40}, {5,50},
        {2, 20}, {3, 30}, {4, 40}, {5, 50}, {1, 10}, {2, 20}, {4, 40}};

newlist1 = {{1, 10}, {2, 20}, {3, 30}, {4, 40}, {5, 50}};
newlist2 = {{2, 20} {3, 30} {4, 40} {5, 50}};
newlist3 = {{1, 10}, {2, 20}, {4, 40}};
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Mary
  • 629
  • 3
  • 10

2 Answers2

11

It's very easy :

 list = {{1, 10}, {2, 20}, {3, 30}, {4, 40}, {5, 50}, {2, 20}, {3, 
        30}, {4, 40} , {5, 50}, {1, 10}, {2, 20}, {4, 40}};

 Split[list, #1[[1]] < #2[[1]] &] 

{
{{1, 10}, {2, 20}, {3, 30}, {4, 40}, {5, 50}},
{{2, 20}, {3, 30}, {4,40}, {5, 50}},
{{1, 10}, {2, 20}, {4, 40}}
}

andre314
  • 18,474
  • 1
  • 36
  • 69
5

Here is a function that is several times faster than Split:

runs[a_List] := Inner[a[[# ;; #2]] &, Prepend[# + 1, 1], Append[#, -1], List] & @
  SparseArray[UnitStep @ Differences @ a[[All, 1]], Automatic, 1]["AdjacencyLists"]

Test:

list = {{1, 10}, {2, 20}, {3, 30}, {4, 40}, {5, 50}, {2, 20}, {3, 30}, {4, 40},
        {5, 50}, {1, 10}, {2, 20}, {4, 40}};

runs[list] // Column
{{1,10},{2,20},{3,30},{4,40},{5,50}}
{{2,20},{3,30},{4,40},{5,50}}
{{1,10},{2,20},{4,40}}
big = Join @@ ConstantArray[list, 100000];

runs[big]                        // Timing // First
Split[big, #1[[1]] <= #2[[1]] &] // Timing // First

0.234

0.78


Related:
- Conditional Gathering of lists
- Find continuous sequences inside a list

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 2
    not something for the casual debugger, though :-) – Yves Klett Jul 31 '13 at 19:40
  • @Mr.Wizard very smart solution! – Mary Aug 01 '13 at 06:54
  • @Mary Thanks; glad you like it. The SparseArray thing is fairly esoteric (and AFAIK undocumented). There are other examples of the use of SparseArray Properties in the second linked post at the bottom of this answer. – Mr.Wizard Aug 01 '13 at 15:22