如何找到列表中最常见元素的百分比?

2024-05-23 15:55:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近一直在使用Counter().most_common,但问题是,我需要将它显示多少的位转换成一个百分比,例如:

[(2, 5), (10, 5)]

致:

[(2, 50%), (10, 50%)]

有没有办法用Counter().most_common或其他方法来实现这一点?

以下是我的部分代码:

    while count < int(DR):
        count = count + int(1)
        DV.append(random.randint(1, int(DI)))
    if count == int(DR):
        print ('\n(The Number that was rolled , the amount of times it came up):')
        global x
        print (Counter(DV).most_common(int((DI))))

Tags: 方法代码mostcountcountercommonint百分比
2条回答
from collections import Counter
l = [1, 1, 2, 2, 2, 2, 2, 3, 4, 10, 10, 10, 10, 10]
c = Counter(l)
[(i, c[i] / len(l) * 100.0) for i in c]

输出,格式为(element, % of total)

[(1, 14.285714285714285),
 (2, 35.714285714285715),
 (3, 7.142857142857142), 
 (4, 7.142857142857142), 
 (10, 35.714285714285715)]

要按顺序列出它们,可以使用collections.Counter.most_common

>>> [(i, c[i] / len(l) * 100.0) for i, count in c.most_common()]
[(2, 35.714285714285715),
 (10, 35.714285714285715),
 (1, 14.285714285714285),
 (3, 7.142857142857142),
 (4, 7.142857142857142)]

如果您没有原始数据,您仍然可以使用Counter来实现这一点。

OrderedDict([(i, str(round(count / sum(c.values()) * 100.0, 3)) + '%') for i, count in c.most_common()])

其中:

  • i是已计数的项
  • count是该项的计数
  • cCounter对象
  • 3是百分比的精度

如果将sum(c.values())移到列表压缩之外,则可以提高性能。

相关问题 更多 >