77077 发表于 2022-7-5 18:37:02

拆分列表

李的作用:

; Iterative Version
;; Group by Number-Lee Mac
;; Groups a list 'l' into a list of lists, each of length 'n'

(defun LM:groupbynum ( l n / a b )
   (while l
       (repeat n
         (setq a (cons (car l) a)
               l (cdr l)
         )
       )
       (setq b (cons (reverse a) b)
             a nil
       )
   )
   (reverse b)
)

 
用法:
_$(LM:groupbynum’(“A”“B”“C”“D”“E”“F”)2)
((“A”“B”)(“C”“D”)(“E”“F”))
 
 
_1$(LM:groupbynum’(“A”“B”“C”“D”“E”“F”)5)
((“A”“B”“C”“D”“E”)(“F”nil nil)
 
我想要:
_1$(LM:groupbynum’(“A”“B”“C”“D”“E”“F”)5)
(“A”“B”“C”“D”“E”)(“F”))

Lee Mac 发表于 2022-7-5 18:47:52

这里有一种可能的方法:
(defun foo ( l n )
   (if l (bar (cons nil l) n n))
)
(defun bar ( l m n )
   (if (and (cdr l) (< 0 n))
       (bar (cons (cons (cadr l) (car l)) (cddr l)) m (1- n))
       (cons (reverse (car l)) (foo (cdr l) m))
   )
)
_$ (foo '(1 2 3 4 5 6) 2)
((1 2) (3 4) (5 6))
_$ (foo '(1 2 3 4 5 6) 3)
((1 2 3) (4 5 6))
_$ (foo '(1 2 3 4 5 6) 4)
((1 2 3 4) (5 6))

Lee Mac 发表于 2022-7-5 18:57:02

另一种迭代方法:
(defun gbn ( l n / a b m )
   (while l
       (setq m n)
       (while (and l (< 0 m))
         (setq a (cons (car l) a)
               l (cdr l)
               m (1- m)
         )
       )
       (setq b (cons (reverse a) b)
             a nil
       )
   )
   (reverse b)
)
_$ (gbn '("A" "B" "C" "D" "E" "F") 5)
(("A" "B" "C" "D" "E") ("F"))

77077 发表于 2022-7-5 19:00:12

 
李,非常感谢!

Tharwat 发表于 2022-7-5 19:07:58

另一个具有mapcar和lambda功能。
 

(defun _split:list (l r / _l _lst)
;; Tharwat 17.09.2015    ;;
(mapcar '(lambda (x)
            (setq _l (cons x _l))
            (if (= (length _l) r)
            (setq _lst (cons (reverse _l) _lst)
                  _l   nil
            )
            )
          )
         l
)
(if _l
   (setq _lst (cons (reverse _l) _lst))
)
(reverse _lst)
)

Lee Mac 发表于 2022-7-5 19:15:17

 
FWIW,由于您没有使用mapcar返回的列表,因此使用foreach循环(尤其是在优化为FAS时)会更有效,即:
(defun foo ( l n / a b i )
   (setq i 0)
   (foreach x l
       (setq a (cons x a)
             i (1+ i)
       )
       (if (zerop (rem i n))
         (setq b (cons (reverse a) b)
               a nil
         )
       )
   )
   (reverse (if a (cons (reverse a) b) b))
)

Tharwat 发表于 2022-7-5 19:18:15

 
感谢您有时间阅读和评论代码。
 
是的,乍一看,mapcar的性能比foreach函数要好得多,尽管我没有在FAS格式的文件中测试它们。
 
无论如何,函数的内容在某种程度上看起来是相同的:
 

(defun _split:list (l r / _l _lst)
(foreach x l
   (setq _l (cons x _l))
   (if (= (length _l) r)
   (setq _lst (cons (reverse _l) _lst)
         _l   nil
   )
   )
)
(reverse (if _l
            (setq _lst (cons (reverse _l) _lst))
            _lst
          )
)
)

77077 发表于 2022-7-5 19:27:22

谢谢李和塔瓦。
 
在你的帮助下,我完成了我的工作。
http://www.cadtutor.net/forum/showthread.php?93867-属性编辑器问题&p=642526&viewfull=1#post642526

Tharwat 发表于 2022-7-5 19:34:38

 
不客气。
 
 
我知道你已经为那个程序创建了这个线程,我真的很高兴你能自己完成它

77077 发表于 2022-7-5 19:38:26

通常都是像剑一样锋利的眼睛。
 
 
谢谢塔瓦。对那个项目有什么建议吗?
页: [1]
查看完整版本: 拆分列表