如何使用Mathematica的Collect/Collect/Transpose函数来转换:
{ { {1, foo1}, {2, foo2}, {3, foo3} }, { {1, bar1}, {2, bar2}, {3, bar3} } } 至
{ {1, foo1, bar1}, {2, foo2, bar2}, {3, foo3, bar3} } 编辑:谢谢!我希望有一个简单的方法,但我猜不是!
发布于 2011-08-08 02:01:49
这是你的清单:
tst = {{{1, foo1}, {2, foo2}, {3, foo3}}, {{1, bar1}, {2, bar2}, {3, bar3}}}这里有一种方法:
In[84]:=
Flatten/@Transpose[{#[[All,1,1]],#[[All,All,2]]}]&@
GatherBy[Flatten[tst,1],First]
Out[84]= {{1,foo1,bar1},{2,foo2,bar2},{3,foo3,bar3}}编辑
这是一个完全不同的版本,只是为了好玩:
In[106]:=
With[{flat = Flatten[tst,1]},
With[{rules = Dispatch[Rule@@@flat]},
Map[{#}~Join~ReplaceList[#,rules]&,DeleteDuplicates[flat[[All,1]]]]]]
Out[106]= {{1,foo1,bar1},{2,foo2,bar2},{3,foo3,bar3}}编辑2个
这是另一种方法,使用链表和内部函数来累积结果:
In[113]:=
Module[{f},f[x_]:={x};
Apply[(f[#1] = {f[#1],#2})&,tst,{2}];
Flatten/@Most[DownValues[f]][[All,2]]]
Out[113]= {{1,foo1,bar1},{2,foo2,bar2},{3,foo3,bar3}}编辑3个
好吧,对于那些认为上述所有内容都太复杂的人来说,这里有一个非常简单的基于规则的解决方案:
In[149]:=
GatherBy[Flatten[tst, 1], First] /. els : {{n_, _} ..} :> {n}~Join~els[[All, 2]]
Out[149]= {{1, foo1, bar1}, {2, foo2, bar2}, {3, foo3, bar3}}发布于 2011-08-08 02:47:35
也许更简单:
tst = {{{1, foo1}, {2, foo2}, {3, foo3}}, {{1, bar1}, {2, bar2}, {3, bar3}}};
GatherBy[Flatten[tst, 1], First] /. {{k_, n_}, {k_, m_}} -> {k, n, m}
(*
-> {{1, foo1, bar1}, {2, foo2, bar2}, {3, foo3, bar3}}
*)发布于 2011-08-08 03:20:21
MapThread
如果保证"foo“和"bar”子列表彼此对齐(就像在示例中一样),并且如果您将考虑使用Gather/Collect/Transpose,以外的函数,那么MapThread就足够了:
data={{{1,foo1},{2,foo2},{3,foo3}},{{1,bar1},{2,bar2},{3,bar3}}};
MapThread[{#1[[1]], #1[[2]], #2[[2]]}&, data]结果:
{{1, foo1, bar1}, {2, foo2, bar2}, {3, foo3, bar3}}模式匹配
如果列表没有对齐,您也可以使用直接的模式匹配和替换(尽管我不建议在大型列表中使用这种方法):
data //.
{{h1___, {x_, foo__}, t1___}, {h2___, {x_, bar_}, t2___}} :>
{{h1, {x, foo, bar}, t1}, {h2, t2}} // FirstSow/Reap
处理未对齐列表的一种更有效的方法是使用Sow和Reap
Reap[Cases[data, {x_, y_} :> Sow[y, x], {2}], _, Prepend[#2, #1] &][[2]]https://stackoverflow.com/questions/6974544
复制相似问题