Re: Collecting like-labelled sublists of a list



Cortez <relativeflux@xxxxxxxxxxxxx> writes:

I need to traverse a list of lists, where each sublist is labelled by
a number, and collect together the contents of all sublists sharing
the same label. So if I have the list -

((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
r) (5 s t))

where the first element of each sublist is the label, I need to
produce -

((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))

I do this with the following -

(defun test (list)
(loop for j in list
for index = (first j)
for k = (rest j)
with indices = nil
if (not (member index indices))
do (pushnew index indices)
and collect k into res
else
do (nconc (nth index res) k)
finally (return res)))

I suspect that there is a more efficient and elegant way of doing
this, however. Any suggestions welcome.

Brief background: this is part of a program I've written for reading
data from SDIF files, a binary format which stores sound description
data. The labelled lists represent partials in spectral analysis data
(partial-index, time, frequency).

I'm a junior lisper, so I tried a different approach mostly for my own
education.


(let ((mylist '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l)
(4 m n) (2 o p) (4 q) (5 s t)))
(ar (make-array 10 :adjustable t)))
(mapcar (lambda (l)
(setf (aref ar (first l))
(append (aref ar (first l)) (rest l)))) mylist))


My choice of 10 for the initial size of the array was arbitrary. I
chose the non-destructive append over nconc, but nconc might be ok.


--
-- Steve
.



Relevant Pages

  • Re: Lists of Figures are consecutively numbered
    ... the format requires that the label not be printed next to the ... If you want three kinds of captions to number independently, ... you will get three separate lists. ... If all your SEQ fields have the same label, or you have not used SEQ fields ...
    (microsoft.public.mac.office.word)
  • Re: counters in list environments
    ... %paralist package doesn't work well with great numbered lists using ... %pitemize environment was defined instead of old itemize environment of ... which informs the kind of the label. ...
    (comp.text.tex)
  • Re: counters in list environments
    ... %paralist package doesn't work well with great numbered lists using ... %pitemize environment was defined instead of old itemize environment of ... which informs the kind of the label. ...
    (comp.text.tex)
  • Re: counters in list environments
    ... %paralist package doesn't work well with great numbered lists using ... %pitemize environment was defined instead of old itemize environment of ... which informs the kind of the label. ...
    (comp.text.tex)
  • Re: parameters of itemized or numbered lists
    ... > and numbered lists. ... > of parameters, optional or mandatory, of the new itemize and enumerate ... The sample label must include *everything*, ... > environment. ...
    (comp.text.tex)