Group Abstract Group Abstract

Message Boards Message Boards

0
|
48 Views
|
3 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Obtain a list of rules from two lists of equal length

Posted 1 day ago

I have two lists, lhs and rhs, which are equal in length. I wish to create a function to transform lhs and rhs into a list of rules, myDesiredList:

lhs = {1, 2, 4, 5, 7};
rhs = {"01", "02", "03", "04", "05"};
myDesiredList = {1 -> "01", 2 -> "02", 4 -> "03", 5 -> "04", 7 -> "05"};

Here's a solution using Map, Rule (i.e., ->), and Transpose:

method1 = Map[#[[1]] -> #[[2]] &, Transpose[{lhs, rhs}]];
method1 == myDesiredList
(* True *)

Is there a simpler or more elegant way to do obtain myDesiredList from lhs and rhs?

By the way, a list of rules can be converted into an association simply by wrapping Association around it:

Association[myDesiredList]
(* <|1 -> "01", 2 -> "02", 4 -> "03", 5 -> "04", 7 -> "05"|> *)
POSTED BY: Andrew D
3 Replies
Posted 12 hours ago

While this is not directly related to the original question I asked, I've realized that if one wishes to ultimately obtain an association from the lists, one can use AssociationThread to go from the lists directly to an association. This obviates the need to create a list of rules as an intermediate step. To summarize:

(* Use Thread or MapThread to obtain a list of rules. *)
Map[myDesiredList == # &,
 {
  (* use Thread (Gianluca Gorni's method) *)
  Thread[lhs -> rhs],
  Thread[Rule[lhs, rhs]],
  
  (* use MapThread (Paul Nielan's method): obtain a list of rules *)
  MapThread[#1 -> #2 &, {lhs, rhs}],
  MapThread[Rule, {lhs, rhs}]
  }]

(* Use Association to create an association from the list of rules. *)
Association[myDesiredList]

(* Use AssociationThread to obtain an association directly from the lists. *)
AssociationThread[lhs -> rhs]
AssociationThread[lhs, rhs]
POSTED BY: Andrew D

I am not aganst Thread:

Thread[lhs -> rhs]
POSTED BY: Gianluca Gorni
Posted 1 day ago

I use

MapThread[Rule, {lhs, rhs}]

And prefer its syntax to Thread.

POSTED BY: Paul Nielan
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard