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
    $\begingroup$ What happens when the sign switches back? A list for each consecutive run of + and -? $\endgroup$ – Carl Woll Feb 3 '18 at 0:08
2
$\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}}}

| improve this answer | |
$\endgroup$
1
$\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.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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