# Replace list element with element from another list based on condition

I Have a list on integers and another list of "duplicates". E.g.

start={{3},{1},{2},{4}}; duplicates={{1,4,7},{5,6}}

I would like to substitute each element of start with the element (if it exists) of duplicates based on the following rule: if the first element at level 2 of an element at level 1 is equal to the element of start, then substitute it.

In this case the result list will be:

result={{3},{1,4,7,},{2},{4}}

• To be clear, if start were {{3},{1},{2},{4},{5},{8}} then the result would be {{3},{1,4,7,},{2},{4},{5,6},{8}}? Apr 22, 2016 at 8:07
• @JasonB exactly. And there is no possibility to find {8} in start Apr 22, 2016 at 8:11
• @JasonB sorry, I mean {7} Apr 22, 2016 at 8:16
• I think the method below should be fine even if there were a {7} in start Apr 22, 2016 at 8:17

You can make a set of replacement rules out of the duplicates list:

rules = ({#[[1]]} -> # & /@ duplicates)
(* {{1} -> {1, 4, 7}, {5} -> {5, 6}} *)


then apply it to any list like the ones you have,

{{3}, {1}, {2}, {4}} /. rules
(* {{3}, {1, 4, 7}, {2}, {4}} *)

{{3}, {1}, {2}, {4}, {5}, {8}} /. rules
(* {{3}, {1, 4, 7}, {2}, {4}, {5, 6}, {8}} *)


Using GroupBy:

start1 /. GroupBy[duplicates, List@First@# &, Flatten]

(*{{3}, {1, 4, 7}, {2}, {4}}*)

start2 /. GroupBy[duplicates, List@First@# &, Flatten]

{{3}, {1, 4, 7}, {2}, {4}, {5, 6}, {8}}


Using Lookup:

start1 = {{3}, {1}, {2}, {4}};
start2 = {{3}, {1}, {2}, {4}, {5}, {8}};


Generate a lookup table:

lut = First@# -> # & /@ duplicates


{1 -> {1, 4, 7}, 5 -> {5, 6}}

Lookup[lut, First@#, #] & /@ start1
Lookup[lut, First@#, #] & /@ start2


{{3}, {1, 4, 7}, {2}, {4}}

{{3}, {1, 4, 7}, {2}, {4}, {5, 6}, {8}}

start = {{3}, {1}, {2}, {4}};
duplicates = {{1, 4, 7}, {5, 6}};

ReplaceAll[MapApply[Sequence[{#} -> {##}] &] @ duplicates] @ start


{{3}, {1, 4, 7}, {2}, {4}}