Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

arrays - Appending to the rows of a table

I have a two dimensional list and a one dimensional list. I would like to insert the 1D list into the 2D list as an additional column. For example:

array = {{a,1,2},{b,2,3},{c,3,4}};
column = {x,y,z};

becomes

final = {{a,1,2,x},{b,2,3,y},{c,3,4,z}};

I have done this inelegantly:

Table[Insert[array[[i]], column[[i]], 4], {i, Length[array]}];

My question: what is the proper way to do this in Mathematica? I don't think it needs the loop I'm using. My solution feels ugly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For example:

 Transpose@Append[Transpose@array, column]

You can also make is a function like so:

 subListAppend = Transpose@Append[Transpose@#1, #2] &;
 subListAppend[array, column]

which makes it easier if you have to use it frequently. And of course if you want to insert at any place other than just the end you can use Insert[].

subListInsert = Transpose@Insert[Transpose@#1, #2, #3] &;
subListInsert[array, column, 2]
--> {{a, x, 1, 2}, {b, y, 2, 3}, {c, z, 3, 4}}

EDIT: Since the obligatory speed optimization discussion has started, here are some results using this and a 10000x200 array:

ArrayFlatten@{{array, List /@ column}}:             0.020 s
Transpose@Append[Transpose@array, column]:          0.067 s
MapThread[Append, {array, column}]:                 0.083 s  
MapThread[Insert[#1, #2, 4] &, {array, column}]:    0.095 s
Map[Flatten, Flatten[{array, column}, {2}]]:        0.26 s
ConstantArray based solution:                       0.29 s
Partition[Flatten@Transpose[{array, column}], 4]:   0.48 s

And the winner is ArrayFlatten!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...