I am trying to find how can do this really quick:

list = {{a, b}, c, {d, e}, f, {g, h}, i}

Desired output List is:

{{a,b,c},{d,e,f},{g,h,i}}

Looks like simple but it takes me plenty of time to think... sorry if this one has been asked before, I didn't find any answer yet.

Also:

Append @@@ Partition[list, 2]
ArrayReshape[list, {3, 3}]
SequenceReplace[{{x_, y__}, z_} :> {x, y, z}]@list
Flatten /@ Partition[list, 2] (* thanks: Okkes Dulgerci *)
{## & @@ #, #2} & @@@ Partition[list, 2]

all give

{{a, b, c}, {d, e, f}, {g, h, i}}

Update: You can also use the undocumented 6th argument of Partition:

Partition[list, 2, 2, {1, -1}, {}, Append]

{{a, b, c}, {d, e, f}, {g, h, i}}

  • 1
    Out of these 3 methods, I'm guessing that ArrayReshape would be the most efficient, right? – Sjoerd Smit Dec 5 '17 at 10:52
  • Thank you! Great answers! – leon365 Dec 5 '17 at 14:03
  • @SjoerdSmit, sorry for late response. Yes, based on limited tests ArrayReshape and Append+Partition combination are the fastest of the four methods. – kglr Dec 20 '17 at 5:13
  • Flatten /@ Partition[list, 2] – Okkes Dulgerci Nov 10 at 2:06
  • Thank you @OkkesDulgerci. – kglr Nov 10 at 21:35
BlockMap[Flatten, list, 2]

Of course, the BlockMap also can be Developer`PartitionMap

  • This should be the most concise one. – Αλέξανδρος Ζεγγ Dec 5 '17 at 8:49
  • Thank you, sir! – leon365 Dec 5 '17 at 14:08
  • I had completely forgotten about this one. Thanks. – Edmund Nov 10 at 1:44

If the input list is consistently dimensioned, then this would work:

list = {{a, b}, c, {d, e}, f, {g, h}, i};
Partition[ Flatten[list, 1], 3]

I hope that this gets you what you need.

  • yes, the pattern is consistent. Thanks for your help, this is work! – leon365 Dec 5 '17 at 3:28
  • 4
    Partition[Flatten[list], 3] is enogh – yode Dec 5 '17 at 9:11

Method I

Step by step

Cases[list, _List]
List /@ Complement[list, %]
Join[%%, %, 2]

give respectively

{{a, b}, {d, e}, {g, h}}

{{c}, {f}, {i}}

{{a, b, c}, {d, e, f}, {g, h, i}}

Method II

Flatten /@ Transpose @ GatherBy[list, Head]

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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