I have list: {{a, b}, {c, d}, {e, f}}
What is the most simple (but automated) way to add this data to the list?
{{a, 0}, {a, b}, {c, 0}, {c, d}, {e, 0}, {e, f}}
You can use a replacement rule like
{{a, b}, {c, d}, {e, f}} /. {x_, y_} :>
Sequence[{x, 0}, {x, y}]
(* {{a, 0}, {a, b}, {c, 0}, {c, d}, {e, 0}, {e, f}} *)
Replace
with a level-spec: Replace[{{a, b}, {c, d}}, {x_, y_} :> Sequence[{x, 0}, {x, y}], 2]
$\endgroup$
A couple of other methods. We take
lst = {{a, b}, {c, d}, {e, f}};
Three directly related ones:
Table[{j {1, 0}, j}, {j, lst}]~Flatten~1
Flatten[{# {1, 0}, #} & /@ lst, 1]
Flatten[{{#1, 0}, {#1, #2}} & @@@ lst, 1]
A relatively concise one using Riffle
:
Riffle[# {1, 0} & /@ #, #] &@lst
And a somewhat silly way:
Hold@Sequence[# {1, 0}, #] & /@ lst // ReleaseHold
Or, from a comment by Gerli:
Apply[Sequence, {# {1, 0}, #}] & /@ lst
Riffle[ #.{{1, 0}, {0, 0}}, #] &@lst
$\endgroup$
Hold[Sequence[...]] // ReleaseHold
you could use Apply[Sequence, {...}]
$\endgroup$
## & @@ {{#, 0}, {##}} & @@@ lst
(+1)
$\endgroup$
## &[{#, 0}, {##}] & @@@ lst
{{a, 0}, {a, b}, {c, 0}, {c, d}, {e, 0}, {e, f}}
list = {{a, b}, {c, d}, {e, f}};
Riffle[MapAt[0 &, {;;, 2}] @ list, list]
{{a, 0}, {a, b}, {c, 0}, {c, d}, {e, 0}, {e, f}}
Splice[{{#, 0}, {##}}] & @@@ lis
{{a, 0}, {a, b}, {c, 0}, {c, d}, {e, 0}, {e, f}}
Another way using Fold
:
lst = {{a, b}, {c, d}, {e, f}};
Fold[Join[#1, {{First@#2, 0}, #2}] &, {}, lst]
(*{{a, 0}, {a, b}, {c, 0}, {c, d}, {e, 0}, {e, f}}*)
MapThread[Sequence,{Thread[List[#[[All,1]],0]],#}]&@lst
(* {{a,0},{a,b},{c,0},{c,d},{e,0},{e,f}} *)
Or
Thread[Hold[Sequence][Thread[List[#[[All,1]],0]],#]]&@lst//ReleaseHold
(* {{a,0},{a,b},{c,0},{c,d},{e,0},{e,f}} *)
list = {{a, b}, {c, d}, {e, f}};
Using Cases
and ReplaceAt
(new in 13.1)
Cases[list, x_ :> Sequence[ReplaceAt[x, _ :> 0, 2], x]]
{{a, 0}, {a, b}, {c, 0}, {c, d}, {e, 0}, {e, f}}
lst={{a, b}, {c, d}, {e, f}};
Another way using ReplaceList
:
ReplaceList[lst,{___,{a_,b_},___}:>Splice@{{a,0},{a,b}}]
{{a,0},{a,b},{c,0},{c,d},{e,0},{e,f}}
Or using SequenceCases
:
SequenceCases[lst,{{a_,b_}}:>Splice@{{a,0},{a,b}}]
{{a,0},{a,b},{c,0},{c,d},{e,0},{e,f}}