Sort a nested list inside and outside in Python
Question:
I am wondering how to sort a nested list in ascending order from both inside the nested list and outside the nested list. Any list comprehension way I can do this easily?
abc = [[6, 2], [7, 1]]
Current working but no good:
list(map(sorted, abc))
[[2, 6], [1, 7]]
Expected output
[[1, 7], [2, 6]]
Answers:
How exactly do you want the outside list to be sorted? I’m assuming you want it sorted by the first elements of the sorted versions of the inner lists (based on your example).
Here’s a comprehension that does that:
abc_sorted = sorted([sorted(sublist) for sublist in abc])
# [[1, 7], [2, 6]]
Note that it first makes a new list that contains a sorted version of each sublist ([sorted(sublist) for sublist in abc]
), and then sorts that new list.
Since sorted()
accepts an iterable, you can also simplify this expression to:
abc_sorted = sorted(sorted(sublist) for sublist in abc)
# [[1, 7], [2, 6]]
Also note that when comparing two lists to determine their sort order, Python compares each subsequent element of the lists in order. You can change this behavior with the key=
parameter.
Final note: you were on the right track with list(map(sorted, abc))
– that applies the sort function to each inner list. When I run that code, it gives me the output [[2, 6], [1, 7]]
, which reflects this behavior (maybe you made a mistake somewhere?). All you have to do is sort the list that gets returned:
list(sorted(map(sorted, abc)))
# [[1, 7], [2, 6]]
I am wondering how to sort a nested list in ascending order from both inside the nested list and outside the nested list. Any list comprehension way I can do this easily?
abc = [[6, 2], [7, 1]]
Current working but no good:
list(map(sorted, abc))
[[2, 6], [1, 7]]
Expected output
[[1, 7], [2, 6]]
How exactly do you want the outside list to be sorted? I’m assuming you want it sorted by the first elements of the sorted versions of the inner lists (based on your example).
Here’s a comprehension that does that:
abc_sorted = sorted([sorted(sublist) for sublist in abc])
# [[1, 7], [2, 6]]
Note that it first makes a new list that contains a sorted version of each sublist ([sorted(sublist) for sublist in abc]
), and then sorts that new list.
Since sorted()
accepts an iterable, you can also simplify this expression to:
abc_sorted = sorted(sorted(sublist) for sublist in abc)
# [[1, 7], [2, 6]]
Also note that when comparing two lists to determine their sort order, Python compares each subsequent element of the lists in order. You can change this behavior with the key=
parameter.
Final note: you were on the right track with list(map(sorted, abc))
– that applies the sort function to each inner list. When I run that code, it gives me the output [[2, 6], [1, 7]]
, which reflects this behavior (maybe you made a mistake somewhere?). All you have to do is sort the list that gets returned:
list(sorted(map(sorted, abc)))
# [[1, 7], [2, 6]]