问题
With the MEMBER I get the searched element and the rest of the LIST. But how did I get the elements befor the searched element is coming?
(CDR (MEMBER 'DURCH '(ZEIT MAL LAENGE DURCH MASSE MAL ZEIT))); with this I get (MASSE MAL ZEIT)
;But how did I get (ZEIT MAL LAENGE)
回答1:
Sometimes these functions are so easy to write and the solution is so transparent to read that there's no point in working out which combination of standard functions will do what you want:
(defun elts-before (l elt &key (test #'eql))
(loop for e in l
until (funcall test e elt)
collect e))
回答2:
The accepted answer is correct (and more efficient), but if you are after standard functions, use LDIFF (i.e. list difference):
(let ((list '(ZEIT MAL LAENGE DURCH MASSE MAL ZEIT)))
(ldiff list (MEMBER 'DURCH list)))
=> (ZEIT MAL LAENGE)
回答3:
You can return both parts with a single traversal:
CL-USER> (defun split-at (item list &key (test #'eql))
(loop :for (x . rest) :on list
:until (funcall test x item)
:collect x :into head
:finally (return (values head rest))))
SPLIT-AT
CL-USER> (split-at 'durch '(a mal b durch c mal d))
(A MAL B)
(C MAL D)
来源:https://stackoverflow.com/questions/58078153/how-can-i-get-the-part-of-a-list-in-front-of-a-special-element