# Combining two lists by key number ## Recommended Posts 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)] )

##### Share on other sites 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
##### Share on other sites Posted (edited)

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
• 1
##### Share on other sites 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)
```

• 1
##### Share on other sites @Lee Mac@ronjonp thank you both guys, works great for what I need it!

## 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. ×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.