4
$\begingroup$

If I have a long list of form

{{1,2,3,4},{5,6,7,8}, ... {97,98,99,100}}

how do I edit/convert it by adding the text as shown below

{{1,2,3,4} -> group1, {5,6,7,8} -> group1, ... {97,98,99,100} -> group3}  

(I want to prepare data for machine learning.)

That is, how to add something (not an element) to the end of an existing sub-list. I've discovered how to read in large datasets suitably prepared in a text editor (using ReadList), but I'm wondering how to do the editing within Mathematica.

Surely this sort of editing is possible but I cannot find how to do it in the Documentation. I'm probably mis-understanding something quite simple.

$\endgroup$
1
  • $\begingroup$ Do you want the output to be a list of replacement rules list -> label or a list of just labels (strings)? $\endgroup$ Sep 1, 2015 at 4:29

2 Answers 2

5
$\begingroup$

I assume the multiplicity of group names in your example is not a typo, that is, you might want to name multiple sublists with the same group. Either way, this will do what you want:

(* example list and group names *)
list = Partition[Range@20, 4];
groups = {"group1", "group1", "group2", "group2", "group3"};
Rule @@@ Transpose[{list, groups}]

(* 
   {{1, 2, 3, 4} -> "group1", {5, 6, 7, 8} -> "group1", 
   {9, 10, 11, 12} -> "group2", {13, 14, 15, 16} -> "group2", 
   {17, 18, 19, 20} -> "group3"} 
*)

n.b. - see Guess who it is's comment re: more direct and canonical way of doing last step. DOH on my part...

$\endgroup$
2
  • 3
    $\begingroup$ Thread[list -> groups] is what I usually do. $\endgroup$ Sep 1, 2015 at 5:21
  • 1
    $\begingroup$ @Guesswhoitis.: Ah, yeah, I herp-a-derped on that obvious and better way - was working on something deep, and over-thought above - you know how that goes... $\endgroup$
    – ciao
    Sep 1, 2015 at 5:29
3
$\begingroup$
SeedRandom[1];list = RandomInteger[100, {6, 4}];
i = 1; j = 1; Sequence @@@ ({# -> "group" <> ToString[i++], #2 -> 
          "group" <> ToString[j++]} & @@@ Partition[list, {2}])
(*{{80, 14, 0, 67} -> "group1", {3, 65, 100, 23} -> 
  "group1", {97, 68, 74, 15} -> "group2", {24, 4, 100, 90} -> 
  "group2", {83, 70, 1, 30} -> "group3", {48, 25, 44, 73} -> "group3"}*)
$\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.