-1

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?

glS
  • 7,623
  • 1
  • 21
  • 61
Vaggelis_Z
  • 8,740
  • 6
  • 34
  • 79
  • 3
    You are no newbie around here (>100 Q´s) -- do you really have no clue as how to go about that? – Yves Klett Oct 17 '16 at 11:43
  • @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. – Vaggelis_Z Oct 17 '16 at 11:46

4 Answers4

9

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

Quantum_Oli
  • 7,964
  • 2
  • 21
  • 43
Wen Chern
  • 716
  • 4
  • 8
6

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.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
1

A simple approach is to use Select:

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

and

lst5 = Select[data, Length[#] == 5 &]
bill s
  • 68,936
  • 4
  • 101
  • 191
1
{lst3, lst5} = GatherBy[data, Length];

enter image description here

ubpdqn
  • 60,617
  • 3
  • 59
  • 148