8
$\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

5 Answers 5

16
$\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$
5
$\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
2
$\begingroup$
list = {{3, 5, 1}, {19, 2, 9}, {4, 3, 1}, {19, 0, 8}};

Using Comap (new in 14.0) and Splice (new in 13.1)

Comap[{Splice @* Sort @* Most, Last}] /@ list

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

Using Query

Query[All, {Splice @* Sort @* Most, Last}] @ list

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

$\endgroup$
2
$\begingroup$
list = {{3, 5, 1}, {19, 2, 9}, {4, 3, 1}, {19, 0, 8}};

Using ReplaceList:

ReplaceList[list, {___, s : {__}, ___} :> {Splice@Sort@Most@s, Last@s}]

(*{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}*)
$\endgroup$

Your Answer

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

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