Replacing commas in the list with an arrow ->

How to replace commas at the second level of the list with replacement arrows?

For example, this:

{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}

For this:

{{a->girl}, {b->girl}, {c->girl}, {e->girl}, {g->girl}}

Replacedoesn't work because he thinks the comma shouldn't be there. Putting it in quotation marks does not work, andStringReplace

I think it should be:

Replace[list, "," -> "->", {2}]
+5
source share
3 answers

The following is the desired result:

lop = {{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}} (* list o' pairs *)

{#1 -> #2}& @@@ lop

For me, this is the most natural way to do this. Here's another way to avoid using a lambda function:

List /@ Rule @@@ lop

Learn more about how to use @@@: In Mathematica, what does @@@ mean?

If you do not like it @@@, you can do this:

{First@# -> Last@#}& /@ lop

And here is another way using the replacement rule:

lop /. {x_,y_}->{x->y}

, , , :

Transpose@{Thread[Rule@@Transpose[lop]]}

( , /. ReplaceAll, /@ Map, @@ Apply, f@x f[x]. )

+9
{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}/.{x_, y_} -> {Rule[x,y]} 

:

{{a -> girl}, {b -> girl}, {c -> girl}, {e -> girl}, {g -> girl}}  

.

!

, ... :

x = ToString[{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}];
y = StringReplace[x, "{" ~~ d_ ~~ ", " ~~ Shortest[f__] ~~ "}" -> 
                     "{" ~~ d ~~ "->" ~~ f ~~ "}"];
z = ToExpression@y

2

List[] Sequence[] - , , Mathematica.

, List[] - , {..,..,..,..} - .

:

 {{a,b},{c,d}} //FullForm  

{a, b} /. List -> Plus
+4

MapApply :

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}
+1

All Articles