5
$\begingroup$

Given

p = {{2, 0}, {3, 0}, {4, 0}, {5, 0}, {8, 0}, {11, 0}}

I want to replace parts according to a second list t1 if the first part is equal but the second part different (first parts in t1 always match first parts in p)

t1 = {{5, 1}, {11, 1}}

Which would give me

{{2, 0}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}

I can do it by

t2 = t1[[All, 1]];
t3 = Flatten[Position[p[[All, 1]], #] & /@ t2];
p[[t3]] = t1;
p

Any ideas for smarter ways (like Replace, ReplacePart, ReplaceList or Cases?

$\endgroup$
2
  • 3
    $\begingroup$ Does Fold[Replace[#1, {#2[[1]], _} -> #2, {1}] &, p, t1] works for you ? $\endgroup$
    – Ben Izd
    Apr 21 at 6:24
  • $\begingroup$ Yes,it does! Thanks! $\endgroup$
    – user57467
    Apr 21 at 9:33

4 Answers 4

4
$\begingroup$
f = Values @ GroupBy[Join @ ##, First, Last] &;

f[p, t1]
{{2, 0}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}
$\endgroup$
1
  • $\begingroup$ Good solution! Great idea! $\endgroup$
    – user57467
    Apr 21 at 10:28
6
$\begingroup$
☺ = # /. ({#, _} -> {##} & @@@ #2) &;

p ~ ☺ ~ t1
{{2, 0}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}
$\endgroup$
4
$\begingroup$
pos = Position[p[[All, 1]], #] & /@ First /@ t1

{{{4}}, {{6}}}

ReplacePart[p, Thread[pos -> t1]]

{{2, 0}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}

$\endgroup$
0
2
$\begingroup$

Slightly different p2 to include duplicates/same t1:

p2 = {{2, 0}, {11, 3}, {3, 0}, {4, 0}, {5, 0}, {8, 0}, {11, 0}}
t1 = {{5, 1}, {11, 1}}

Create a list of rules:

t2 = Replace[t1, {x_, y_} :> {x, Blank[]}, {1}]
rules = MapThread[Rule, {t2, t1}

{{5, _}, {11, _}}

{{5, _} -> {5, 1}, {11, _} -> {11, 1}}

Apply rules:

p2 /. rules

{{2, 0}, {11, 1}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}

I think this is more easily modifiable than my other approach.

$\endgroup$
1
  • $\begingroup$ Very Good! I like your idea! $\endgroup$
    – user57467
    Apr 22 at 0:47

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.