本文介绍了如果元素在lisp的两个给定列表中,则返回它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果元素在两个给定列表中,我该如何返回?
How can i return elements if they are in two given lists?
示例:
L1 = (a b c d e a b c) L2 = (a d f g k c c) Result = (a a a c c c c d d)我想删除两个列表中都没有的元素,然后附加结果列表
I want to remove elements that arent in both lists and, then, append the resultant lists
推荐答案您可以从哈希表开始,将一个列表元素映射到一对,第一个元素是第一个列表中的元素,第二个是第二个列表中的元素.然后收集元素:
You can start with a hash table, mapping a list element to a pair, first being elements from the first list, second - elements from the second. Then you collect the elements:
(defun common-elements (l1 l2 &key (test 'eql)) (let ((ht (make-hash-table :test test)) ret) (dolist (e l1) (let ((pair (gethash e ht))) (if pair (push e (car pair)) (setf (gethash e ht) (cons (list e) nil))))) (dolist (e l2) (let ((pair (gethash e ht))) (when pair ; no need to store e when it is not in l1 (push e (cdr pair))))) (maphash (lambda (e pair) (declare (ignore e)) (when (cdr pair) ; we know (car pair) is non-nil (setq ret (nconc (car pair) (cdr pair) ret)))) ht) ret)) (common-elements '(a b c d e a b c) '(a d f g k c c)) ==> (A A A C C C C D D)请注意,未未定义返回列表元素的顺序.
Note that the order in which the list elements are returned is not defined.
更多推荐
如果元素在lisp的两个给定列表中,则返回它们
发布评论