本帖最后由 llsheng_73 于 2024-12-4 13:47 编辑
N维表排序及自定义顺序
http://bbs.mjtd.com/forum.php?mo ... 6244&fromuid=202795
(出处: 明经CAD社区)
- (defun sortn(l funs)
- (or(listp(car l))(setq l(mapcar'list l)))
- (or(listp funs)(setq funs(list funs)))
- (while(<(length funs)(length(car l)))
- (setq funs(cons(car funs)funs)))
- (vl-sort l'(lambda(x y / n)(setq n 0)
- (while(and(=(car x)(car y))(cdr x)(cdr y))(setq x(cdr x)y(cdr y)n(1+ n)))((nth n funs)(car x)(car y)))))
(setq lst'("DIE_2_PW" "PH_1_PW" "PS_2_PW" "PH_PW" "DIE_1_PW" "DIE_PW" "PS_1_PW" "PS_PW"))
对它进行处理,以便后续排序
(setq l(mapcar'(lambda(x / l)(if(cddr(setq l(mapcar'(lambda(x)(if(VL-SYMBOLP x)(VL-SYMBOL-NAME x)x))(read(strcat"("(VL-STRING-TRANSLATE"_"" "x)")")))))
l(list(car l)0(cadr l))))lst))
接下来对l进行排序并对应表原始数据表
(mapcar'(lambda(x)(nth(vl-position x l)lst))
(sortn l(List < < <)))
("DIE_PW" "DIE_1_PW" "DIE_2_PW" "PH_PW" "PH_1_PW" "PS_PW" "PS_1_PW" "PS_2_PW")
也可以按其它方式排序,比如DIE,PS,PH进行降序,其它按升序
(mapcar'(lambda(x)(nth(vl-position x l)lst))
(sortn l(List > < <)))
("PS_PW" "PS_1_PW" "PS_2_PW" "PH_PW" "PH_1_PW" "DIE_PW" "DIE_1_PW" "DIE_2_PW")
也可以使用帖子中最后一个,自定义序列排序,不过在这里意义不大,但可能实现比较自由的自定义序列
- (defun sortn(l keys funs fuzz / n mposition);;;keys关键字列号要么为nil要么为表,funs各个关键字的排序方式,通常为<或>,也可以为自定义序列,比如'("张三""李四")
- (defun mposition(e l / i)(if(setq i(vl-position e l))i(length l)))
- (or(listp(car l))(setq l(mapcar'list l)))
- (or(listp funs)(setq funs(list funs)))
- (if(zerop(setq n(length keys)))(setq n(length(car l))))
- (while(<(length funs)n)(setq funs(cons(car funs)funs)))
- (mapcar(function(lambda(x)(nth x l)))
- (vl-sort-i(if keys(mapcar(function(lambda(x)(mapcar'(lambda(y)(nth y x))keys)))l)l)
- (function(lambda(x y / n )(setq n 0)
- (while(and(equal(car x)(car y)fuzz)(cdr x)(cdr y))(setq x(cdr x)y(cdr y)n(1+ n)))
- (if(listp(setq n(nth n funs)))
- (<(mposition(car x)n)(mposition(car y)n))
- (n(car x)(car y))))))))
(mapcar'(lambda(x)(nth(vl-position x l)lst))
(SORTN l NIL '(("PS""DIE""PH")(0 1 2))0))
("PS_PW" "PS_1_PW" "PS_2_PW" "DIE_PW" "DIE_1_PW" "DIE_2_PW" "PH_PW" "PH_1_PW")
(mapcar'(lambda(x)(nth(vl-position x l)lst))
(SORTN l '(0 1) '(("PS""DIE""PH")(1 0 2))0))
("PS_1_PW" "PS_PW" "PS_2_PW" "DIE_1_PW" "DIE_PW" "DIE_2_PW" "PH_1_PW" "PH_PW")
(mapcar'(lambda(x)(nth(vl-position x l)lst))
(SORTN l '(1 0) '((1 0 2)("PS""DIE""PH"))0))
("PS_1_PW" "DIE_1_PW" "PH_1_PW" "PS_PW" "DIE_PW" "PH_PW" "PS_2_PW" "DIE_2_PW")
|