How do I replace the commas on the second level of a list with replacement arrows?
For example, this:
{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}
To this:
{{a->girl}, {b->girl}, {c->girl}, {e->girl}, {g->girl}}
Replace
doesn't work because it thinks the comma shouldn't be there. Putting it in quotes doesn't work, nor does StringReplace
What I think it should be:
Replace[list, "," -> "->", {2}]
The following gives the desired result:
lop = {{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}} (* list o' pairs *)
{#1 -> #2}& @@@ lop
To me that's the most natural way to do it. Here's another way that avoids the use of a lambda function:
List /@ Rule @@@ lop
More on that way of using @@@
: In Mathematica, what does @@@ mean?
If you don't like @@@
you can do this:
{First@# -> Last@#}& /@ lop
And here's yet another way, using a replacement rule:
lop /. {x_,y_}->{x->y}
And, what the heck, here's the least intuitive way I can think of to do it:
Transpose@{Thread[Rule@@Transpose[lop]]}
(Note that /.
is shorthand for ReplaceAll
, /@
is shorthand for Map
, @@
is shorthand for Apply
, and f@x
is just another way to write f[x]
.)
{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}/.{x_, y_} -> {Rule[x,y]}
Result:
{{a -> girl}, {b -> girl}, {c -> girl}, {e -> girl}, {g -> girl}}
These things are explained under the tutorials for patterns and transformation rules in the help system.
HTH!
Edit
You CAN do it by using Strings ... but it is not the right way:
x = ToString[{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}];
y = StringReplace[x, "{" ~~ d_ ~~ ", " ~~ Shortest[f__] ~~ "}" ->
"{" ~~ d ~~ "->" ~~ f ~~ "}"];
z = ToExpression@y
Edit 2
The List[]
and the Sequence[]
are two constructs that you must understand to start working with Mathematica.
Replacing the braces or the comma in a List is not possible, because List[]
is a function and the {..,..,..,..}
is just notation.
Try the following to understand it:
{{a,b},{c,d}} //FullForm
and
{a, b} /. List -> Plus
MapApply
works nicely here:
In[1]:= Rule @@@ {{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}
Out[1]= {a -> girl, b -> girl, c -> girl, e -> girl, g -> girl}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With