4
$\begingroup$

I have a list, say,

cc = {{0.16441114380905922, 1}, {0.16441114380905922, 2},
      {-0.16441114381135857, 4}, {0.3469323902621586, 3},
      {-0.3469323902254179, 2}, {-0.26126804383825986, 3},
      {0.2612680438599802, 2}, {-0.28969854537720147, 3},
      {0.28969854538168743, 2}, {-7.968690709137364, 3},
      {7.968690708910122, 2}, {-4.000091496006696, 3},
      {4.000091495616817, 2}, {4.729024444062355, 3},
      {-4.72902444452141, 2}, {4.729024444062355, 1}}

I want to get the following information:

  1. all the $2\times1$ sub-lists with the same first element should be together (e.g., {x,y} and {x,z} should be together)
  2. multiplicity of the first elements

I am using Tally and Sort (also used GatherBy) but not much help so far. Thanks in advance.

$\endgroup$
0

2 Answers 2

9
$\begingroup$
GatherBy[cc, #[[1]] &]
Length /@ GatherBy[cc, #[[1]] &]
$\endgroup$
3
  • 8
    $\begingroup$ GatherBy[cc, First] might be easier to read. $\endgroup$
    – Sasha
    Commented Sep 11, 2012 at 23:16
  • $\begingroup$ @Sasha True, but also less general; I applaud belisarius for using Part, though mentioning First is appreciated. $\endgroup$
    – Mr.Wizard
    Commented Sep 12, 2012 at 10:40
  • 1
    $\begingroup$ @Mr.Wizard hehe Glad you remember ... now I already was criticized both ways :) $\endgroup$ Commented Sep 12, 2012 at 17:19
3
$\begingroup$

A solution using Gather:

{#, Length /@ #}& @ Gather[cc, First@#1 === First@#2 &]

{{{{0.164411, 1}, {0.164411, 2}}, {{-0.164411, 4}}, {{0.346932, 3}}, {{-0.346932, 2}}, {{-0.261268, 3}}, {{0.261268, 2}}, {{-0.289699, 3}}, {{0.289699, 2}}, {{-7.96869, 3}}, {{7.96869, 2}}, {{-4.00009, 3}}, {{4.00009, 2}}, {{4.72902, 3}, {4.72902, 1}}, {{-4.72902, 2}}}, {2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1}}

$\endgroup$

Your Answer

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