Message Boards Message Boards

0
|
4956 Views
|
4 Replies
|
2 Total Likes
View groups...
Share
Share this post:

How to change elements in list using another list as dictionary

Posted 10 years ago

Good day!

I have two datasets: first -list (1000x3) which contains 'X' 'Y' 'Z' values (they have only 10 various combinations), second is list (10x2) contains 'X' 'Y' 'Z' combinations and 'ID'. I need to change 'X' 'Y' 'Z' to 'ID' and take list 1000x1. For example first list is A and second is B.

A = {{1, 2, 3}, {1, 3, 1}, {13, 15, 0}, {13, 15, 0}, {0, 0, 0}, {1, 3,
     1}, {0, 0, 0}};
B = {{{1, 2, 3}, 0}, {{1, 3, 1}, 1}, {{13, 15, 0}, 2}, {{0, 0, 0}, 3}}

and I need to take a result as

{0, 1, 2, 2, 3, 1, 3}

Thanks a lot for your help

Anton

POSTED BY: Anton Ekimenko
4 Replies
Posted 10 years ago

Thank you for the detailed explanation. Now it more clearly for me!!! Especially "Rule@@@B" (earlier I never used this form).

Anton

POSTED BY: Anton Ekimenko
Posted 10 years ago

You are welcome. With FullForm[B] you can see that B is in fact:

List[List[List[1,2,3],0],List[List[1,3,1],1],List[List[13,15,0],2],List[List[0,0,0],3]]

If you replace the List heads shown in bold with Rule you end up with

List[Rule[List[1,2,3],0],Rule[List[1,3,1],1],Rule[List[13,15,0],2],Rule[List[0,0,0],3]]

Which is the replacement rule that you need:

{{1, 2, 3} -> 0, {1, 3, 1} -> 1, {13, 15, 0} -> 2, {0, 0, 0} -> 3}

This operation can be done with Apply[Rule, B, {1}]. This head replacing operation is so common that there is a shortcut for it: Rule@@@B

Then you just apply the replacement rule with /.

POSTED BY: Gustavo Delfino
Posted 10 years ago

Dear Gustavo,

Yes it realy work in my case!!! Thank you very much. At first time I can't understand how this code work because I'm not experienced user of Mathematica. But I'll try to understand it myself.

POSTED BY: Anton Ekimenko
Posted 10 years ago

Try with:

A /. Rule @@@ B
POSTED BY: Gustavo Delfino
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract