I have a nested list:
{{9, 8, 7}, {8, 7, 6}, {7, 6, 5}, {6, 5, 4}, {5, 4, 3}, {4, 3, 2}, {3, 2, 1}}
I need to sort the lists within the list to create:
{{7, 8, 9}, {6, 7, 8}, {5, 6, 7}, {4, 5, 6}, {3, 4, 5}, {2, 3, 4}, (1, 2, 3}}
How do I do this?
You want the Map
function, which applies a function to each element of a list.
That is, Map[f, {1, 2, 3}]
gives {f[1], f[2], f[3]}
.
In this case, you can use Map[Sort, list]
. Map
also has an infix operator, /@
:
In[1]:= Map[Sort, {{9, 8, 7}, {8, 7, 6}, {7, 6, 5}, {6, 5, 4},
{5, 4, 3}, {4, 3, 2}, {3, 2, 1}}]
Out[1]= {{7, 8, 9}, {6, 7, 8}, {5, 6, 7}, {4, 5, 6},
{3, 4, 5}, {2, 3, 4}, {1, 2, 3}}
In[2]:= Sort /@ {{9, 8, 7}, {8, 7, 6}, {7, 6, 5}, {6, 5, 4},
{5, 4, 3}, {4, 3, 2}, {3, 2, 1}}
Out[2]= {{7, 8, 9}, {6, 7, 8}, {5, 6, 7}, {4, 5, 6},
{3, 4, 5}, {2, 3, 4}, {1, 2, 3}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With