繁体   English   中英

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

[英]How do i find the percentage of the most common element in a list?

我最近一直在使用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))))
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())移出列表压缩之外,则可以提高性能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM