我有一个像这样的列表:
'(("Alpha" . 1538)
("Beta" . 8036)
("Gamma" . 8990)
("Beta" . 10052)
("Alpha" . 12837)
("Beta" . 13634)
("Beta" . 14977)
("Beta" . 15719)
("Alpha" . 17075)
("Rho" . 18949)
("Gamma" . 21118)
("Gamma" . 26923)
("Alpha" . 31609))
如何计算列表中每个元素的汽车中这些术语出现的总数?基本上我想要:
(("Alpha" . 4)
("Beta" . 5)
("Gamma" . 3)
("Rho" . 1))
不,这不是家庭作业。我只是还没有“思考Lisp”的东西。
在C#中,我将使用LINQ来做到这一点。我也可以使用while循环之类的方法来进行Lisp操作,但是我想做的方式似乎过于复杂。
编辑
这就是我所拥有的:
(defun count-uniq (list)
"Returns an alist, each item is a cons cell where the car is
a unique element of LIST, and the cdr is the number of occurrences of that
unique element in the list. "
(flet ((helper (list new)
(if (null list)
new
(let ((elt (assoc (car list) new)))
(helper (cdr list)
(if elt
(progn (incf (cdr elt)) new)
(cons (cons (car list) 1) new)))))))
(nreverse (helper list nil))))
最佳答案
我不知道这是最优雅的,但似乎是合理的:
(defun add-for-cheeso (data)
(let (result)
(dolist (elt data result)
(let ((sofar (assoc (car elt) result)))
(if sofar
(setcdr sofar (1+ (cdr sofar)))
(push (cons (car elt) 1) result))))))
关于emacs - 优雅的物品计数方式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6050033/