8
$\begingroup$

Suppose I have some list like the following form

$ \{ j[two, 1,1,1,1], j[two,2,2,2,2], j[two,3,3,3,3] \}$

list = {j[two, 1, 1, 1, 1], j[two, 2, 2, 2, 2], j[two, 3, 3, 3, 3]}

I want to change this list into the form

$\{ \{two, \{1,1,1,1\} \}, \{two, \{2,2,2,2\}\}, \{two, \{3,3,3,3\}\}$

For the individual, I can do this by

 List@@j[two,List[1,1,1,1]]

But I want to deal with the whole $ \{ j[two, 1,1,1,1], j[two,2,2,2,2], j[two,3,3,3,3] \}$ and obtain the desired results

Any ideas?

$\endgroup$

6 Answers 6

8
$\begingroup$
g = {#, {##2}} &;

1.

g @@@ list
{{two, {1, 1, 1, 1}}, {two, {2, 2, 2, 2}}, {two, {3, 3, 3, 3}}}

2.

list /. j -> g
{{two, {1, 1, 1, 1}}, {two, {2, 2, 2, 2}}, {two, {3, 3, 3, 3}}}

3.

Block[{j = g}, list]
{{two, {1, 1, 1, 1}}, {two, {2, 2, 2, 2}}, {two, {3, 3, 3, 3}}}

4.

With[{j = g}, Evaluate @ list]
{{two, {1, 1, 1, 1}}, {two, {2, 2, 2, 2}}, {two, {3, 3, 3, 3}}}
$\endgroup$
7
$\begingroup$
list = {j[two, 1, 1, 1, 1], j[two, 2, 2, 2, 2], j[two, 3, 3, 3, 3]}

{First@#, List @@ Rest@#} & /@ list

{{two, {1, 1, 1, 1}}, {two, {2, 2, 2, 2}}, {two, {3, 3, 3, 3}}}

$\endgroup$
6
$\begingroup$
list = {j[two, 1, 1, 1, 1], j[two, 2, 2, 2, 2], j[two, 3, 3, 3, 3]}

list /. j[x__] :> {First[{x}], Rest[{x}]}
$\endgroup$
2
  • 1
    $\begingroup$ Also list /. j[x_, y__] :> {x, {y}} $\endgroup$ May 1, 2023 at 14:35
  • $\begingroup$ Shoot that was even better $\endgroup$ May 1, 2023 at 14:41
5
$\begingroup$
Cases[list,j[x_,y__]:> {x,{y}}]

(* {{two, {1, 1, 1, 1}}, {two, {2, 2, 2, 2}}, {two, {3, 3, 3, 3}}} *)
$\endgroup$
3
$\begingroup$
list = {j[two, 1, 1, 1, 1], j[two, 2, 2, 2, 2], j[two, 3, 3, 3, 3]};

Using Comap (new in 14.0)

Comap[{First, Rest}] /@ List @@@ list

Using Query and MapApply (new in 13.1)

Query[All, {First, Rest}] @ MapApply[List] @ list

Both produce

{{two, {1, 1, 1, 1}}, {two, {2, 2, 2, 2}}, {two, {3, 3, 3, 3}}}

$\endgroup$
3
$\begingroup$
list = {j[two, 1, 1, 1, 1], j[two, 2, 2, 2, 2], j[two, 3, 3, 3, 3]};

Using SequenceCases:

SequenceCases[list, {a_@b__} :> {First@{b}, Rest@{b}}]

{{two, {1, 1, 1, 1}}, {two, {2, 2, 2, 2}}, {two, {3, 3, 3, 3}}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.