5
$\begingroup$

Given

t7 = t8 = {{3, 5, 1}, {19, 2, 9}, {4, 3, 1}, {19, 0, 8}};

I want to Sort the first two numbers in each sublist and keep the third number in its position. I can do it by

t7[[All, {1, 2}]] = Sort /@ t7[[All, {1, 2}]]
t7

or

 t8[[All, {1, 2}]] = # & /@ #[[Ordering[#]]] & /@ t8[[All, 1 ;; 2]]
 t8

to get

{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}

But there must be more elegant ways to do it. Any idea?

$\endgroup$
0

3 Answers 3

15
$\begingroup$

You can use SubsetMap for this:

SubsetMap[Sort,{1,2}] /@ {{3,5,1}, {19,2,9}, {4,3,1}, {19,0,8}}

{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}

$\endgroup$
1
  • $\begingroup$ Thank you! Good function! Didn't know it. $\endgroup$
    – user57467
    Aug 28, 2021 at 3:39
7
$\begingroup$
Append[Sort@Most@#, Last@#]& /@ t7

Or with Through:

Flatten@Through[{Sort@*Most, Last}@#] & /@ t7
$\endgroup$
4
$\begingroup$

Let sf2 stand for sortfirst2,

sf2 = # /. {a_, b_, c___} /; a > b -> {b, a, c} &

t7 = {{3, 5, 1}, {19, 2, 9}, {4, 3, 1}, {19, 0, 8}};

sf2 /@ t7

{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}
$\endgroup$
1
  • 3
    $\begingroup$ Or Replace[t7, {a_, b_, c___} /; a > b -> {b, a, c}, 1] (to act only at level 1) or t7 /. {a_, b_, c___} /; a > b -> {b, a, c} (because the condition makes it so that the entire expression doesn't change and it goes to subexpressions). $\endgroup$
    – march
    Aug 27, 2021 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.