4
$\begingroup$

I have a list of the following kind:

{{1,0.5},{2,0.6},{3,0.8},{-4,0.9},{-3,0.95}}

The important property is, that somewhere in the list, the first element of the sublists changes sign (above is from + to -, but could be from - to +). How can I most efficiently split this into two lists:

{{1,0.5},{2,0.6},{3,0.8}}

and

{{-4,0.9},{-3,0.95}}

?

$\endgroup$
1
  • 1
    $\begingroup$ What happens when the sign switches back? A list for each consecutive run of + and -? $\endgroup$
    – Carl Woll
    Commented Feb 3, 2018 at 0:08

2 Answers 2

3
$\begingroup$
list = {{1, 0.5}, {2, 0.6}, {3, 0.8}, {-4, 0.9}, {-3, 0.95}};

SplitBy[#, Sign[First @ #] &] & @ list

{{{1, 0.5}, {2, 0.6}, {3, 0.8}}, {{-4, 0.9}, {-3, 0.95}}}

Or

Split[#,  SameQ @@ Sign [First /@ {##}] &] & @ list

{{{1, 0.5}, {2, 0.6}, {3, 0.8}}, {{-4, 0.9}, {-3, 0.95}}}

$\endgroup$
2
$\begingroup$

This works on your example data, but it might not be general enough to satisfy you, but it is the best I can do with only one example.

data = {{1, 0.5}, {2, 0.6}, {3, 0.8}, {-4, 0.9}, {-3, 0.95}};
Column[{d1, d2} = SplitBy[data, Sign @* First]]

split

Column, of course, is only used form display.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.