ant*_*nio 3 lisp elisp list duplicates
我用它来查找列表重复:
(defun have-dups (x)
(let ((dups (copy-tree x)))
(if (eq (length (delete-dups dups)) (length x))
nil
t)))
(have-dups (list 1 2 3 3)) ;=> t
(have-dups (list 1 2 3)) ;=> nil
Run Code Online (Sandbox Code Playgroud)
考虑到copy-tree
和的开销delete-dups
,可能有更好的方法.
使用哈希表,只要找到哈希表中已存在的元素,就知道你有重复项:
(defun has-dup (list)
(block nil
(let ((hash (make-hash-table :test 'eql)))
(map ()
(lambda (item)
(if (gethash item hash)
(return t)
(setf (gethash item hash) t)))
list))))
Run Code Online (Sandbox Code Playgroud)