robierzo 发表于 2022-7-6 07:29:12

convert list with mapcar, lamb

I need to convert a list:
(51 41 83 10 60 32 46 84)
 
to list:
((51 41)(83 10)(60 32)(46 84))
 
Regards

marko_ribar 发表于 2022-7-6 07:35:23

(defun every2nd ( lst ) (vl-remove nil (mapcar '(lambda ( a ) (if (eq (rem (vl-position a lst) 2) 0) a)) lst)))(defun groupby2 ( lst ) (mapcar '(lambda ( a b ) (list a b)) (every2nd lst) (every2nd (cdr lst))))(groupby2 '(51 41 83 10 60 32 46 84))
 
M.R.

David Bethel 发表于 2022-7-6 07:37:10

Maybe :
 
 
 

(setq lst '(51 41 83 10 60 32 46 84))(defun lby2 (l / tmp) (while l   (setq tmp (cons (list (nth 0 l) (nth 1 l)) tmp)         l (cdr l)         l (cdr l)))(reverse tmp))
 
 
I would recommend doing some basic error checking for these types of routine
 
ie is the length of the list an even number.
 
-David

Gu_xl 发表于 2022-7-6 07:40:04

(defun every2 (l) (cond ((and (car l) (cadr l)) (cons (list (car l) (cadr l)) (every2 (cddr l))))((car l) (list l)) ))

Lee Mac 发表于 2022-7-6 07:43:08

(defun g2 ( l ) (if l (cons (list (car l) (cadr l)) (g2 (cddr l)))))

Lee Mac 发表于 2022-7-6 07:47:56

 
Be careful with duplicates...

_$ (every2nd '(1 2 3 1 2 3))(1 3 1 3)For your method, consider perhaps:

(defun f ( l / i )   (setq i -1)   (vl-remove-if '(lambda ( x ) (= 1 (rem (setq i (1+ i)) 2))) l))(defun g2 ( l ) (mapcar 'list (f l) (f (cdr l))))
_$ (g2 '(1 2 3 1 2 3))((1 2) (3 1) (2 3))

Stefan BMR 发表于 2022-7-6 07:49:54

Three alternatives
1 - recursive - similar to Lee (see l2p function)
 
2- using foreach

(defun ph1:l2p (l / s r) (foreach x l   (if s      (setq r (cons (list s x) r)            s nil      )      (setq s x)   ) ) (reverse r))3 - using repeat

(defun ph2:l2p (l / r) (repeat (/ (length l) 2)   (setq r (append r (list (list (car l) (cadr l))))         l (cddr l)   ) ) r)

robierzo 发表于 2022-7-6 07:52:17

Uffff. I will explore all options, to see which one i choose.
I thought it would be easier with mapcar and lambda.
Thank you all.
Regards.

Lee Mac 发表于 2022-7-6 07:57:27

 
Note that not all tasks are best solved using mapcar.
For this particular example, the items in the list need to be processed in pairs, hence mapcar is not best suited for the task since it will process every item in a list consecutively, meaning that you must first manipulate the list before passing it to mapcar. This extra work to manipulate the list is very inefficient where other methods could process the list directly.
 
The mapcar function is just one tool in your AutoLISP toolbox, from which you should choose the best tool for the job. Restricting yourself to solely using mapcar for every task would be like building a house with just a hammer...

robierzo 发表于 2022-7-6 08:00:01

O.K. making way....Thanks
页: [1] 2
查看完整版本: convert list with mapcar, lamb