Jump to content
gsc

Insert list2 in list1 at certain position

Recommended Posts

gsc

I have 2 lists:

List1 (0.0 -0.196738 0.0 0.196738 0.0 0.0)

List2 (-0.059895 0.120221 -0.059895 0.0)

 

I want to insert List2 in List1 at a certain position:

NewList (0.0 -0.196738 0.0 -0.059895 0.120221 -0.059895 0.0 0.196738 0.0 0.0)

In this case at position nth 3

 

How do I do this?

Share this post


Link to post
Share on other sites
Tharwat

Hi,

 

Just an example for you comprehend the process:

 

(setq list1 '(0.0 -0.196738 0.0 0.196738 0.0 0.0)
     list2 '(-0.059895 0.120221 -0.059895 0.0)
)
(setq position 3)
(setq run 0)

(foreach item list1
 (if (= (setq run (1+ run)) position)
   (foreach element list2
     (setq lst (cons element lst))
   )
   (setq lst (cons item lst))
 )
)

Share this post


Link to post
Share on other sites
Tharwat

Another if you want to. :)

 

(setq pos 3)

(mapcar '(lambda (u) (if (= (length lst) pos) (mapcar '(lambda (x) (setq lst (cons x lst))) list2)
                      (setq lst (cons u lst))))
       list1)

Share this post


Link to post
Share on other sites
Lee Mac

For example:

(defun foo ( new pos lst / tmp )
   (repeat pos (setq tmp (cons (car lst) tmp) lst (cdr lst)))
   (append (reverse tmp) new lst)
)

_$ (setq l1 '(0 1 2 3 4 5))
(0 1 2 3 4 5)
_$ (setq l2 '("a" "b" "c"))
("a" "b" "c")
_$ (foo l2 3 l1)
(0 1 2 "a" "b" "c" 3 4 5)

Share this post


Link to post
Share on other sites
Stefan BMR

A recursive solution

(defun inslist (l1 n l2 / f)
 (defun f (l n)
   (if
     (and l (> n 0))
     (cons (car l) (f (cdr l) (1- n)))
     (append l2 l)
   )
 )
 (f l1 n)
)

 

(setq l1 '(0.0 -0.196738 0.0 0.196738 0.0 0.0)
     l2 '(-0.059895 0.120221 -0.059895 0.0)
)

(inslist l1 3 l2) -> (0.0 -0.196738 0.0 -0.059895 0.120221 -0.059895 0.0 0.196738 0.0 0.0)

Share this post


Link to post
Share on other sites
Lee Mac

Or, without the subfunction -

(defun foo ( new pos lst )
   (if (and (< 0 pos) lst)
       (cons (car lst) (foo new (1- pos) (cdr lst)))
       (append new lst)
   )
)

Share this post


Link to post
Share on other sites
gsc

Thanx, all examples work!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×