Jump to content

Combining two lists by key number


Recommended Posts

lastknownuser

Need a little help with some list combining. I have two lists:

(1 2 3 4)
( (1 a) (2 b) (2 c) (2 d) (3 e) (4 f) )

And I want to combine them to one list, by key number, like this:

( [1 (1 a)] [2 (2 b) (2 c) (2 d)] [3 (3 e)] [4 (4 f)] )

Link to post
Share on other sites
lastknownuser
Posted (edited)

I came up with something like this quickly, but I can't figure out how to group second list by one key number.

(defun c:test ( / n m len1 len2 list3 list4)
  (setq list1 (list "1" "2" "3"))
	(setq list2 (list '("1" "a") '("2" "b") '("2" "c") '("2" "d") '("3" "e") ))
        (setq n 0)
        (setq len1 (length list1))
        (setq len2 (length list2))
        (while (< n len1)
	    (setq m 0)
	    (while (< m len2)
	    (if (= (nth n list1) (nth 0 (nth m list2)) )
		(progn
		   (setq list3 (list (nth n list1) (nth m list2)))
		   (setq list4 (cons list3 list4))
);progn
);if
(setq m (+ m 1))
);while
(setq n (+ n 1))
);while
(reverse list4)
);defun



The result is:
(("1" ("1" "a")) ("2" ("2" "b")) ("2" ("2" "c")) ("2" ("2" "d")) ("3" ("3" "e"))
But I need the lists with number 2 all grouped, like this ("2" ("2" "b") ("2" "c") ("2" "d"))

Edited by lastknownuser
Link to post
Share on other sites
Lee Mac

Consider the following -

(defun foo ( a b / y )
    (setq a (mapcar 'list a))
    (foreach x (reverse b)
        (if (setq y (assoc (car x) a))
            (setq a (subst (vl-list* (car x) x (cdr y)) y a))
        )
    )
    a
)

 

For example:

_$ (foo '("1" "2" "3" "4") '(("1" "a") ("2" "b") ("2" "c") ("2" "d") ("3" "e") ("4" "f")))
(("1" ("1" "a")) ("2" ("2" "b") ("2" "c") ("2" "d")) ("3" ("3" "e")) ("4" ("4" "f")))

 

I'm unsure how you wish to handle these cases:

_$ (foo '("1" "2" "3" "4" "5") '(("1" "a") ("2" "b") ("2" "c") ("2" "d") ("3" "e") ("4" "f")))
(("1" ("1" "a")) ("2" ("2" "b") ("2" "c") ("2" "d")) ("3" ("3" "e")) ("4" ("4" "f")) ("5"))

_$ (foo '("1" "2" "3" "4") '(("1" "a") ("5" "f")))
(("1" ("1" "a")) ("2") ("3") ("4"))

 

Edited by Lee Mac
  • Like 1
Link to post
Share on other sites
ronjonp

Another for fun:

(setq l '(("1" "a") ("2" "b") ("2" "c") ("2" "d") ("3" "e")))
(setq k '("1" "2" "3"))
(mapcar '(lambda (x) (cons x (vl-remove-if-not '(lambda (y) (= x (car y))) l))) k)

 

  • Like 1
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...