[英]How to sort a list with sublists (common Lisp)
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<)
To sort on all elements of a sublist, use a custom function for the sort predicate or key . 要对子列表的所有元素进行排序,请使用自定义函数作为排序谓词或键 。 Change the sort predicate to a custom function that can determine the order of two sublists.
将排序谓词更改为可以确定两个子列表顺序的自定义函数。 Alternatively, change the sort key to a custom function that reduces the sublist to a sortable value.
或者,将排序键更改为自定义函数,将子列表减少为可排序值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.