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

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

问题描述

我有一个二维列表和一个一维列表.我想将一维列表作为附加列插入到二维列表中.例如:

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

我这样做很不雅:

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

我的问题:在 Mathematica 中执行此操作的正确方法是什么?我认为它不需要我正在使用的循环.我的解决方案感觉很丑.

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]

如果您必须经常使用它,这会更容易.当然,如果你想在除末尾以外的任何地方插入,你可以使用 Insert[].

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

由于强制性速度优化讨论已经开始,以下是使用 这个 和一个 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天全站免登陆