I am just wondering:
given a list {{{3,1,2},{4,2,5}},{{7,1},{2,4}}}
, I want to sort the first component, then have the second开发者_如何学编程 component change as the first one does. The desired result is {{{1,2,3},{2,5,4}},{{1,7},{4,2}}}
.
How can I do this? Many thanks for your help.
Here's the job-security-ensuring one-liner =)
In[16]:= list={{{3,1,2},{4,2,5}},{{7,1},{2,4}}};
In[17]:= {#[[Ordering[#]]],#2[[Ordering[#]]]}& @@@ list
Out[17]= {{{1,2,3},{2,5,4}},{{1,7},{4,2}}}
This might be a little more clear as to what's happening:
sorter[{a_, b_}] :=
Module[{order = Ordering[a]},
{a[[order]], b[[order]]}
]
In[19]:= sorter /@ list
Out[19]= {{{1, 2, 3}, {2, 5, 4}}, {{1, 7}, {4, 2}}}
I suggest:
#[[ All, Ordering@#[[1]] ]] & /@ list
This is shorter than Michael's, and nearly twice as efficient.
micSort = {#[[Ordering[#]]], #2[[Ordering[#]]]} & @@@ # &;
wizSort = #[[All, Ordering@#[[1]]]] & /@ # &;
a = RandomInteger[100, {2400, 2, 15}];
micSort@a === wizSort@a
First@Timing@Do[#@a, {25}] & /@ {micSort, wizSort}
Out[1]= True
Out[2]= {0.453, 0.282}
精彩评论