如果元素在lisp的两个给定列表中,则返回它们

编程入门 行业动态 更新时间:2024-10-26 17:36:22
本文介绍了如果元素在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的两个给定列表中,则返回它们

本文发布于:2023-10-20 08:58:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1510515.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   两个   列表中   lisp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!