gsc 发表于 2022-7-5 15:41:54

在certa的列表1中插入列表2

我有两个列表:
列表1(0.0-0.196738 0.0 0.196738 0.0 0.0)
列表2(-0.059895 0.120221-0.059895 0.0)
 
我想在列表1的某个位置插入列表2:
新列表(0.0-0.196738 0.0-0.059895 0.120221-0.059895 0.0 0.196738 0.0 0.0)
在这种情况下,在位置nth 3处
 
我该怎么做?

Tharwat 发表于 2022-7-5 15:53:04

你好
 
举个例子,让你了解这个过程:
 

(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))
)
)

Tharwat 发表于 2022-7-5 16:06:19

如果你愿意的话,再来一杯。
 

(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)

Lee Mac 发表于 2022-7-5 16:21:05

例如:
(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)

Stefan BMR 发表于 2022-7-5 16:26:01

递归解
(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)

Lee Mac 发表于 2022-7-5 16:40:37

或者,没有子功能-
(defun foo ( new pos lst )
   (if (and (< 0 pos) lst)
       (cons (car lst) (foo new (1- pos) (cdr lst)))
       (append new lst)
   )
)

gsc 发表于 2022-7-5 16:43:03

Thanx,所有示例都有效!
页: [1]
查看完整版本: 在certa的列表1中插入列表2