Count how many different values a list takes in Mathematica

坚强是说给别人听的谎言 提交于 2019-12-03 06:58:01

Just for amusement, all the following commands also give the desired result:

Length@Gather@l

Length@Union@l

Length@Tally@l

Count[BinCounts@l, Except@0]

Count[BinLists@l, Except@{}]

Length@Split@Sort@l

Length@GatherBy[l, # &]

Length@Split@SortBy[l, # &]

And many more, of course.

Edit

Here is a little timing experiment (not serious)

l = RandomInteger[{1, 10^2}, 10^7];
t2[x_] := {Timing[x], ToString[HoldForm@x]};
SetAttributes[t2, HoldAll]
Grid[Reverse /@
  {t2[Length@DeleteDuplicates[l]],
   t2[Length@Tally[l]],
   t2[Length@Gather[l]],
   t2[Count[BinCounts[l], Except@0]],
   t2[Length@Union[l]],
   t2[Length@Split@Sort@l],
   t2[Count[BinLists[l], Except@0]]},
 Frame -> All]

BTW: Note the difference between BinLists[ ] and BinCounts[ ]

Edit

A more detailed view of DeleteDuplicates vs Tally

t = Timing;
ListLinePlot@Transpose@
  Table[l = RandomInteger[{1, 10^i}, 10^7];
   {Log@First@t@Length@DeleteDuplicates@l,
    Log@First@t@Length@Tally@l},
   {i, Range[7]}]

Beware! Log Plot!

Use DeleteDuplicates (or Union in older versions) to remove duplicate elements. You can then count the elements in the returned list.

In[8]:= Length[DeleteDuplicates[a]]
Out[8]= 5

In[9]:= Length[DeleteDuplicates[b]]
Out[9]= 2
Length[DeleteDuplicates[a]]

would do the trick. Depending on what else you're going to do, you could use Union or Tally instead of DeleteDuplicates.

CountDistinct[a]

would also do the trick, which is a function introduced in Mathematica 10.0, a function equivalent to

Length[DeleteDuplicates[a]]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!