How to sort a list with sublists?
(setq list '((0) (1) (2) (0 1 5) (0 1 3) (0 1 5) (0 3 0) (0) (1)
(2 7 19) (0 0 3 0)))
; restricting the sort to only the first element:
(sort (copy-seq list) #'< :key #'car)
--> ((0) (0 1 5) (0 1 3) (0 1 5) (0 3 0) (0) (0 0 3 0) (1) (1) (2) (2 7 19))
The output I am looking for is sort on all elements of the sublist:
--> ((0) (0) (0 0 3 0) (0 1 3) (0 1 5) (0 1 5) (0 3 0) (1) (1) (2) (2 7 19))
Start by defining a function that determines whether one list is less than another. The following example assumes that the lists can only contain numbers:
(defun list< (a b)
(cond ((null a) (not (null b)))
((null b) nil)
((= (first a) (first b)) (list< (rest a) (rest b)))
(t (< (first a) (first b))) ))
Armed with this function, you can now sort the list of lists.
(sort (copy-seq list) #'list<)
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