计算列表在数学中所需的不同值 [英] Count how many different values a list takes in Mathematica
本文介绍了计算列表在数学中所需的不同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取在列表中找到的不同值的数量。
I would like to get the number of different values found in a List.
例如:
a = {1,2,3,4,5}
的输出为5,而 b = { 1,1,1,2,2}
。
推荐答案
命令还给出所需的结果:
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, # &]
当然还有更多。
编辑
这是一个小小的时间实验(不严重)
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:注意 BinLists []
code> BinCounts []
BTW: Note the difference between BinLists[ ]
and BinCounts[ ]
编辑
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]}]
当心!
这篇关于计算列表在数学中所需的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文