2
$\begingroup$

Suppose I have the following list:

 list = {{1,3.4},{2,6.7},{3,0},{1,2},{2,8.6},{3,7.9},{1,0},{2,7.8},{3,5}};

I will like to sort the list by the first term in the order they are presented on the list like the following:

 {{1,3.4},{1,2},{1,0},{2,6.7},{2,8.6},{2,7.8},{3,0},{3,7.9},{3,5}}. 

Finally I will like to make three different list which select the cases starting with certain number as:

list1 = {{1,3.4},{1,2},{1,0}}
list2 = {{2,6.7},{2,8.6},{2,7.8}}
list3 = {{3,0},{3,7.9},{3,5}}
$\endgroup$
3
  • 1
    $\begingroup$ Look up GatherBy[]. $\endgroup$ Commented Dec 11, 2015 at 20:55
  • $\begingroup$ Thanks! It helped for the fist part. Now, how can I create a list with only the cases that start for example by 1? $\endgroup$
    – fermi
    Commented Dec 11, 2015 at 21:11
  • $\begingroup$ Why doesn't GatherBy[data, First] not solve your problem completely? $\endgroup$
    – m_goldberg
    Commented Dec 22, 2015 at 3:15

1 Answer 1

2
$\begingroup$
list = {{1, 3.4}, {2, 6.7}, {3, 0}, {1, 2}, {2, 8.6}, {3, 7.9}, {1, 0}, {2, 7.8}, {3, 5}}

{list1, list2, list3} = GatherBy[list, First];

The more general way is

res = GatherBy[list, First];

and then get a particular part with f.e.

res[[2]]

{{2, 6.7}, {2, 8.6}, {2, 7.8}}

$\endgroup$
2
  • $\begingroup$ Thanks! Is there a more general way? I have from 1 to 200. I can write list1, list2,...list200 but it would take long. $\endgroup$
    – fermi
    Commented Dec 11, 2015 at 21:17
  • $\begingroup$ see update ------- $\endgroup$
    – eldo
    Commented Dec 11, 2015 at 21:28

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.