How to sort an already sorted array by a second property?
Question:
Lets say I have a list of tuples, and by calling sort where key = first element, our list comes back as:
[(1, 'e'), (2, 'd'), (3, 'c'), (3, 'a'), (3, 'b'), (4, 'f')]
Now, how do I apply a sort that applies only to those values where the first values match, (in this case, the three values that have first element as 3), so that the final list is:
[(1, 'e'), (2, 'd'), (3, 'a'), (3, 'b'), (3, 'c'), (4, 'f')]
I have applied a sort to the first element, but when I apply a sort to the second element, the first sort becomes undone. I would like to keep the original sort, and change ONLY those elements with duplicate first elements.
Thank you!
Answers:
The default .sort()
method in Python already does this. For example, the code:
L = [(1, 'e'), (2, 'd'), (3, 'c'), (3, 'a'), (3, 'b'), (4, 'f')]
L.sort()
print(L)
Returns [(1, 'e'), (2, 'd'), (3, 'a'), (3, 'b'), (3, 'c'), (4, 'f')]
which is what you want
Lets say I have a list of tuples, and by calling sort where key = first element, our list comes back as:
[(1, 'e'), (2, 'd'), (3, 'c'), (3, 'a'), (3, 'b'), (4, 'f')]
Now, how do I apply a sort that applies only to those values where the first values match, (in this case, the three values that have first element as 3), so that the final list is:
[(1, 'e'), (2, 'd'), (3, 'a'), (3, 'b'), (3, 'c'), (4, 'f')]
I have applied a sort to the first element, but when I apply a sort to the second element, the first sort becomes undone. I would like to keep the original sort, and change ONLY those elements with duplicate first elements.
Thank you!
The default .sort()
method in Python already does this. For example, the code:
L = [(1, 'e'), (2, 'd'), (3, 'c'), (3, 'a'), (3, 'b'), (4, 'f')]
L.sort()
print(L)
Returns [(1, 'e'), (2, 'd'), (3, 'a'), (3, 'b'), (3, 'c'), (4, 'f')]
which is what you want