[英]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
是该项目的计数; c
是Counter
对象 3
是百分比的精确度 如果将sum(c.values())
移出列表压缩之外,则可以提高性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.