Lisp 什么';按值对哈希表排序的最佳方法是什么?
现在,我必须先将hastable复制到列表中,然后再对其进行排序:Lisp 什么';按值对哈希表排序的最佳方法是什么?,lisp,clisp,Lisp,Clisp,现在,我必须先将hastable复制到列表中,然后再对其进行排序: (defun good-red () (let ((tab (make-hash-table)) (res '())) (dotimes (i 33) (setf (gethash (+ i 1) tab) 0)) (with-open-file (stream "test.txt") (loop for line = (read-line stream nil) u
(defun good-red ()
(let ((tab (make-hash-table)) (res '()))
(dotimes (i 33) (setf (gethash (+ i 1) tab) 0))
(with-open-file (stream "test.txt")
(loop for line = (read-line stream nil)
until (null line)
do
(setq nums (butlast (str2lst (substring line 6))))
(dolist (n nums) (incf (gethash n tab)))
))
**(maphash #'(lambda (k v) (push (cons k v) res)) tab)**
(setq sort-res (sort res #'< :key #'cdr))
(reverse (nthcdr (- 33 18) (mapcar #'car sort-res))) ))
(德芬良红()
(let((制表符(生成哈希表))(res'())
(dotimes(i33)(setf(gethash(+i1)选项卡)0))
(打开文件(流“test.txt”)
(行的循环=(读取行流nil)
直到(空行)
做
(setq nums(butlast(str2lst(子字符串行6)))
(数据列表(n nums)(incf(gethash n tab)))
))
**(映射哈希#’(lambda(k v)(推(cons k v)res))选项卡)**
(setq排序分辨率(排序分辨率<:键cdr))
(倒车档(nthcdr(-3318)(mapcar#'car sort res)))
顺便说一句,获取列表前N个元素的更好方法是什么?哈希表本身就是无序的。如果希望对其进行排序,则需要使用内容初始化某种排序的有序数据结构
如果您想获取序列的前N个元素,则始终存在SUBSEQ。Vatine的答案在技术上是正确的,但对于有人问这个问题的直接问题可能没有太大帮助。使用哈希表保存计数器集合,然后按分数选择前N项的常见情况如下:
;; convert the hash table into an association list
(defun hash-table-alist (table)
"Returns an association list containing the keys and values of hash table TABLE."
(let ((alist nil))
(maphash (lambda (k v)
(push (cons k v) alist))
table)
alist))
(defun hash-table-top-n-values (table n)
"Returns the top N entries from hash table TABLE. Values are expected to be numeric."
(subseq (sort (hash-table-alist table) #'> :key #'cdr) 0 n))
第一个函数将哈希表的内容作为列表中的一系列cons'd对返回,该列表称为关联列表(键/值对的典型列表表示)。大多数Lisp爱好者手头上已经有了这个函数的变体,因为这是一个非常常见的操作。这个版本来自图书馆,它在CL社区中被广泛使用
第二个函数使用SUBSEQ从列表中获取前N个项目,该列表是通过使用每对的CDR作为键对第一个函数返回的列表进行排序而返回的。将:键更改为#'car将按散列键排序,将#'>更改为#'<将颠倒排序顺序。您的问题是什么?标题中的那个,还是内容中的那个?回答标题中的那个和/或评论中的那个不是更有建设性吗?