簡體   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