3

I have a list of the form:

lstA = { 
         { {"a","b"}, -1.5}, 
         { {"c","d"}, -2  }   
       }

I wanto to add another value to each sublist that comes from another list

lstB = {-5,-10}

I would like the final list to look like

 mergeList =  { 
            { {"a","b"}, -1.5, -5 }, 
            { {"c","d"}, -2,-10 }
            }

I have tried using Append to get each sublist, and then append the value corresponding value from lstB:

  Append[{#1, #2} & @@@ lstA, lstB] 
olliepower
  • 2,254
  • 2
  • 21
  • 34

3 Answers3

8

The most efficient approach uses (new in ver.6) ArrayFlatten:

ArrayFlatten[{{lstA, Transpose[{lstB}]}}]
{{{"a", "b"}, -1.5, -5}, {{"c", "d"}, -2, -10}}

Instead of threading Append which is not very efficient, another much faster way would use also Transpose twice and Append only once:

Transpose @ Append[ Transpose @ lstA, lstB]

or alternatively one could exploit the second argument of Join using Transpose only once:

Join[ lstA, Transpose[{lstB}], 2]

In the Front-end Transpose can be is rewritten (using Esc+ tr + Esc) in especially terse (neat) way, e.g.:

enter image description here

Moreover we have:

enter image description here

Artes
  • 57,212
  • 12
  • 157
  • 245
6

You can do that using MapThread:

mergeList = MapThread[Append, {lstA, lstB}]
celtschk
  • 19,133
  • 1
  • 51
  • 106
2

Since I like to stick with my ideas, here is an example with Insert:

Insert[lstA[[#1]], #2, #3] & @@@ Thread[{Range@Length@lstA, lstB, {3, 3}}]
{{{"a", "b"}, -1.5, -5}, {{"c", "d"}, -2, -10}}
Öskå
  • 8,587
  • 4
  • 30
  • 49