问题
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?
回答1:
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}}
回答2:
It may be useful to be aware that Ordering will also work
lst = {{9, 8, 7}, {8, 7, 6}, {7, 6, 5}, {6, 5, 4}, {5, 4, 3}, {4, 3,
2}, {3, 2, 1}};
Map[#[[Ordering[#]]] &, lst]
But for this type of example the approach is slower than Map/Sort
lst2 = RandomInteger[100, {10^5, 3}];
Map[Sort, lst2]; // Timing
Map[#[[Ordering[#]]] &, lst2]; // Timing
{0.175955, Null}
{1.02087, Null}
Ordering can be useful for sorting by position
lst3 = {{a1, 4, c1}, {a2, 3, c2}, {b3, 1, d3}, {e4, 2, f4}};
lst3[[Ordering[lst3[[All, -2]]]]] // MatrixForm
来源:https://stackoverflow.com/questions/4222472/sorting-lists-inside-nested-lists