How to get min / max list using key

Currently, I have a list of objects, each of which contains a specific attribute. I would like to get a list item with a min attribute value. Is there a concise way to do this?

The python equivalent will look something like this: min(d, key=d.get)

Is there any way to get min / max N elements?

+6
source share
2 answers
 CL-USER 8 > (reduce #'min '((1) (-1) (3)) :key #'first) -1 

or

 CL-USER 9 > (loop for e in '((1) (-1) (3)) minimize (first e)) -1 

I am afraid the container element is more complicated:

 CL-USER 9 > (defun minimum (list predicate key) (when list (let* ((m0 (first list)) (m1 (funcall key m0))) (mapc (lambda (e0 &aux (e1 (funcall key e0))) (when (funcall predicate e1 m1) (psetf m0 e0 m1 e1))) list) m0))) MINIMUM CL-USER 10 > (minimum '((a 1) (b -1) (c -2)) #'< #'second) (C -2) CL-USER 11 > (minimum '((a 1) (b -1)) #'< #'second) (B -1) CL-USER 12 > (minimum '((a 1)) #'< #'second) (A 1) CL-USER 13 > (minimum '() #'< #'second) NIL 
+10
source

Use the function provided by the Alexandria : extremum library .

 (extremum '((a 3) (b 1) (c 2)) #'< :key #'second) => (B 1) 
+1
source

Source: https://habr.com/ru/post/987325/


All Articles