簡體   English   中英

Python計算列表中的出現次數:如何使其更快?

[英]Python counting occurrence in a list: how to make it faster?

我有一個包含大約600萬個項目的字符串列表,並且我試圖計算每個唯一值的出現次數。

這是我的代碼:

lines = [6 million strings]
unique_val = list(set(lines))    # contains around 500k items

mydict = {}
for val in unique_val:
    mydict[val] = lines.count(val)

考慮到我要計算的列表很大,我發現上述代碼的運行速度非常慢。

我想知道是否有辦法使其更快?

非常感謝

如果您不想使用collections模塊。

counts = dict()
for line in lines:
    counts[line] = counts.get(line,0) + 1

或者,如果您不想使用Counter

from collection import defaultdict
counts = defaultdict(int)
for line in lines:
    counts[line] += 1

這個怎么樣,

from collections import defaultdict
import collections

lines = [600 million strings]

d = defaultdict(int)
for line in lines:
    for word, count in collections.Counter(line).items():
        d[word] += count

脾氣暴躁的解決方案

我認為numpy使用unique會給您最快的答案:

result = dict(zip(*np.unique(lines, return_counts=True)))

Numpy在引擎蓋下進行了大量優化。 根據鏈接的文檔,魔術圈圍繞return_counts標志:

return_counts :布爾值,可選

如果為True,則還返回ar中每個唯一值出現的次數。


定時

我選擇了您最初的方法,反方法

result = Counter(lines)

和由生成的集合上的numpy方法

N = 1000000
lines = [chr(i%100) for i in range(N) ]

顯然,該測試的覆蓋面不是很大,但這只是一個開始。

您的進近速度為0.584秒; DeepSpace的Counter為0.162( 3.5倍加速 ),numpy為0.0861( 7倍加速 )。 同樣,這可能取決於很多因素,包括您擁有的數據類型:結論可能是numpy或Counter將提供加速,而counter不需要外部庫

調用list.count非常昂貴。 字典訪問(O(1)攤銷時間)和in運算符相對便宜。 以下代碼片段顯示了更好的時間復雜度。

def stats(lines):
    histogram = {}
    for s in lines:
        if s in histogram:
            histogram[s] += 1
        else:
            histogram[s] = 1
    return histogram

暫無
暫無

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

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