-1
$\begingroup$

Suppose we have the following list

data = {{1, 2, 3}, {4, 3, 2, 1, 0}, {6, 7, 8}, {-5, -4, -3, -2, -1}, 
        {-2, -3, -4}, {1, 1, 1, 1, 1}}

As we can see, some of the sublists have 3 elements, while others have 5 elements. I want the following: create two new lists lts3 and lst5 one with the 3-elements sublists and the other with all the 5-elements sublists.

lst3 = {{1, 2, 3}, {6, 7, 8}, {-2, -3, -4}};
lst5 = {{4, 3, 2, 1, 0}, {-5, -4, -3, -2,- 1}, {1, 1, 1, 1, 1}}

Any ideas?

$\endgroup$
  • 3
    $\begingroup$ You are no newbie around here (>100 Q´s) -- do you really have no clue as how to go about that? $\endgroup$ – Yves Klett Oct 17 '16 at 11:43
  • $\begingroup$ @YvesKlett I see your point. Surely I can find a way to solve this issue but I'm always looking for new elegant and quick solutions. $\endgroup$ – Vaggelis_Z Oct 17 '16 at 11:46
9
$\begingroup$

GatherBy[exp, Length] would work. Here exp is the expression.

$\endgroup$
6
$\begingroup$

In recent versions I would turn to GroupBy for this:

GroupBy[data, Length] /@ {3, 5}

Note: Lookup can be somewhat faster than Map.

If memory consumption is a concern consider using the older Sow and Reap as you can preselect the targets, e.g. Reap[Sow[#, Length@#] & ~Scan~ data, {3, 5}][[2, All, 1]] See Defining Tags in Reap.

$\endgroup$
  • $\begingroup$ GroupBy is a nice function. This made me think of you :) $\endgroup$ – ubpdqn Oct 18 '16 at 8:54
  • $\begingroup$ @ubpdqn I guess that makes me forgotten bastard? ;-) -- thanks for the laugh. :^) $\endgroup$ – Mr.Wizard Oct 18 '16 at 10:03
  • $\begingroup$ Nice use of tags in Sow, thanks for that! $\endgroup$ – AndreasP Oct 18 '16 at 11:09
1
$\begingroup$
{lst3, lst5} = GatherBy[data, Length];

enter image description here

$\endgroup$
1
$\begingroup$

A simple approach is to use Select:

lst3 = Select[data, Length[#] == 3 &]

and

lst5 = Select[data, Length[#] == 5 &]
$\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.