簡體   English   中英

有沒有更快的方法可以計算列表中某個數字的出現次數?

[英]Is there a faster way I can count the number of occurrences of a number in a list?

我正在嘗試編寫一個函數來計算列表中某個數字的出現次數,並且順序根據數字升序(從 0 到列表中的最大值),而不是出現次數。 這是我寫的函數:

def sort_counts(sample):
    result = []
    for i in range(max(sample)+1):
        result.append(sample.count(i))
    return result

例如:

>>> sort_counts([1,2,2,3,3,4,1,1,1,1,2,5])
>>> [0, 5, 3, 2, 1, 1]

我了解到,如果列表中有更多數字, sample.count會運行緩慢。 有沒有更快/更簡單的方法可以編寫這個函數?

集合模塊中的計數器是一種計算列表中項目出現次數的好方法

from collections import Counter
lst = [1,2,2,3,3,4,1,1,1,1,2,5]
# create a counter object
c = Counter(lst)
# get the counts
[c[i] for i in range(max(c)+1)]
# [0, 5, 3, 2, 1, 1]

如果您不想使用計數器,則可以在事先創建適當大小的結果數組后簡單地迭代列表中的值:

sample = [1,2,2,3,3,4,1,1,1,1,2,5]
result = [0] * (max(sample)+1)
for v in sample:
    result[v] += 1

輸出:

[0, 5, 3, 2, 1, 1]

對於您的樣本數據,速度明智,如果Counter解決方案是1x時間,這大約是4x而您現有的解決方案大約是8x 隨着列表變長, Counter的速度優勢降低,相對性能更像1x2x4x

如果您不想使用 count 遍歷樣本的元素並更新結果。 它可以減少查找元素計數所需的多次遍歷所需的時間。

def sort_counts(sample):
    result = [0]*(max(sample)+1)
    for s in samples:
        result[s]+=1
    return result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM