附加到一个表中的行 [英] Appending to the rows of a table

查看:258
本文介绍了附加到一个表中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个两维列表和一个一维列表。我想插入一维表到2D列表作为附加列。例如:

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};

变为

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.

推荐答案

例如:

 Transpose@Append[Transpose@array, column]

您还可以是一个函数,像这样:

You can also make is a function like so:

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

这使得它更容易,如果你经常使用它。当然,如果你想在不仅仅是你可以使用结束插入[]

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

编辑:由于强制性的速度优化的讨论已经开始,这里有一些成果使用<一个href=\"http://stackoverflow.com/questions/4198961/what-is-in-your-mathematica-tool-bag/4199042#4199042\">this和10000x200数组:

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

和获奖者是 ArrayFlatten

这篇关于附加到一个表中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆