3
$\begingroup$

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] 
$\endgroup$
3
  • 1
    $\begingroup$ Have you looked at Insert or do you need Append? $\endgroup$
    – Öskå
    Apr 29, 2014 at 16:18
  • $\begingroup$ I have been trying Append. Append should work because I want to get each sublist then append the value from lstB $\endgroup$
    – olliepower
    Apr 29, 2014 at 16:19
  • $\begingroup$ Very closely related: (13748) $\endgroup$
    – Mr.Wizard
    Apr 30, 2014 at 2:01

3 Answers 3

7
$\begingroup$

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

$\endgroup$
6
$\begingroup$

You can do that using MapThread:

mergeList = MapThread[Append, {lstA, lstB}]
$\endgroup$
1
  • $\begingroup$ @MichaelE2: Thank you. $\endgroup$
    – celtschk
    Apr 29, 2014 at 16:30
2
$\begingroup$

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}}
$\endgroup$

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