Reputation: 40
I have a list of D-dimensional points (where D is a constant), and I would like to sort them first based on the 1st dimension values, then by the 2nd dimesion values and so on, so if 2 points have the same values at the first x dimensions, they would be sorted based on the values of dimension x+1.
I know that if my number of dimension is final, I could use this solution: https://stackoverflow.com/a/37111840 But since I have D dimensions where D is a constant number in the code, I'm not sure how to define the sorting "key" values well.
Upvotes: 1
Views: 510
Reputation: 5549
As @iz_ points out, this is how python sorting works by default. Here is an example illustrating this point:
import itertools
import random
# generate all length 3 tuples of 0s 1s and 2s
foo = list(itertools.product(*([range(3)]*3)))
#mix them all up
random.shuffle(foo)
print(foo)
# this sorts by the first, then the second, then the last
foo.sort()
print(foo)
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]
Upvotes: 1
Reputation: 1064
example list l1 with three dimensions:
l1 = [[0, 3, 0], [0, 0, 3], [1, 0, 3], [2, 2, 1], [2, 1, 1], [2, 1, 0], [1, 0, 0], [2, 0, 0], [1, 1, 2], [1, 2, 3]]
l2 = sorted(l1, key = lambda k: k[::-1])
print(l2)
[[1, 0, 0], [2, 0, 0], [2, 1, 0], [0, 3, 0], [2, 1, 1], [2, 2, 1], [1, 1, 2], [0, 0, 3], [1, 0, 3], [1, 2, 3]]
I'm not sure whether that's exactly the sort order that you wanted, but it keys on k values of arbitrary length (as long as all elements of l1 are the same length).
Upvotes: 0