Visual LISP, AutoLISP and General Customization
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

List combination with common attribute

3 REPLIES 3
SOLVED
Reply
Message 1 of 4
Iraklis2009
294 Views, 3 Replies

List combination with common attribute

Hello everybody,

 

From what I'll say you'll understand that I have the solution right before my eyes... I am so so stuck right now.

 

I have two lists with lists inside:

 

((A) (A) (A) (B) (B) (B) (B) (C) (C))

 

and

 

((A 1) (A 2) (A 3) (B 1) (B 2) (B 3) (B 4) (C 1) (C 2))

 

I just want to make a list with lists that is:

 

((A 1 2 3) (B 1 2 3 4) (C 1 2))

 

I am guessing mapcar and lambda should come into play but i can't figure it out.

 

Any solution is more than welcome.

Thank you.

3 REPLIES 3
Message 2 of 4
Lee_Mac
in reply to: Iraklis2009

Perhaps a 'GroupByAssoc' function:

 

(defun LM:GroupByAssoc ( l / a r )
    (while l
        (setq r
            (if (setq a (assoc (caar l) r))
                (subst (cons (car a) (append (cdr a) (cdar l))) a r)
                (cons  (car l) r)
            )
            l (cdr l)
        )
    )
    (reverse r)
)

 

Example:

 

_$ (LM:GroupByAssoc '((A 1) (A 2) (A 3) (B 1) (B 2) (B 3) (B 4) (C 1) (C 2)))
((A 1 2 3) (B 1 2 3 4) (C 1 2))

 

Message 3 of 4
Iraklis2009
in reply to: Lee_Mac

Dear Lee_Mac,

Kudos to you.

Worked like a charm.

A mile thanks.

 

Just a question.

Is there any reason I should reverse the list? - apart from having it in the original order.

Message 4 of 4
Lee_Mac
in reply to: Iraklis2009

You're very welcome!


Iraklis2009 wrote:

Just a question.

Is there any reason I should reverse the list? - apart from having it in the original order.


I assume you refer to the final expression in my function: (reverse r)?

 

This is to return the result in the correct order, since the list 'r' is constructed in reverse using the cons function. The reverse / cons combination is used since it is far faster than append to achieve the same result.

 

Lee

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk Design & Make Report

”Boost