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

11 投票
2 回答
17507 浏览
提问于 2025-04-18 10:08

我最近在使用 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))))

2 个回答

0

如果你没有原始数据,也可以仅通过使用 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()) 移到列表压缩外面,性能会更好。

36
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]

输出的格式是 (元素, 占总数的百分比)

[(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)]

撰写回答