9
$\begingroup$

Consider the following list:

data={4078, 256, -1266, -388, 1290, 1368, 1446, 1524, 2};

I would like to split any kind of such list always, when figures turn form negative to positive. In the case of data the result would be:

{{4078, 256, -1266, -388},{ 1290, 1368, 1446, 1524, 2}}

I tried it with

Split[%, #2>0 && #1<0 &]

but I got:

{{4078}, {256}, {-1266}, {-388, 1290}, {1368}, {1446}, {1524}, {2}}
$\endgroup$
13
$\begingroup$

Try

Split[data, Not[#2>0 && #1<0] &]

Note that Split[list, test] splits list between two elements when test fails. In this case you want to to split the list iff #2>0 && #1<0 &[e1, e2] == True which is equivalent to Not[#2>0 && #1<0]&[e1, e2] == False.

$\endgroup$
1
  • $\begingroup$ Heike, you are indeed a great help! :) $\endgroup$ – John Apr 12 '12 at 22:32
9
$\begingroup$

Probably the tersest way to write it

Split[data, ! #1 < 0 < #2 &]
$\endgroup$
8
$\begingroup$

Alternately:

In[277]:= Split[data, Sign[{##}] != {-1, 1} &]

Out[277]= {{4078, 256, -1266, -388}, {1290, 1368, 1446, 1524, 2}}

In[276]:= Split[data, GreaterEqual @@ Sign[{##}] &]

Out[276]= {{4078, 256, -1266, -388}, {1290, 1368, 1446, 1524, 2}}
$\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.