3
$\begingroup$

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}}
$\endgroup$
  • $\begingroup$ 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}}? $\endgroup$ – Jason B. Apr 22 '16 at 8:07
  • $\begingroup$ @JasonB exactly. And there is no possibility to find {8} in start $\endgroup$ – Fabio Sist Apr 22 '16 at 8:11
  • $\begingroup$ @JasonB sorry, I mean {7} $\endgroup$ – Fabio Sist Apr 22 '16 at 8:16
  • $\begingroup$ I think the method below should be fine even if there were a {7} in start $\endgroup$ – Jason B. Apr 22 '16 at 8:17
5
$\begingroup$

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}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.