[英]Fastest way to count the occurance of a string
我正在計算從文本文件中獲取的一些字符串。 我已經做到了,但是我想知道還有沒有其他可以快速找到的方法。 下面是我的代碼:
首先,我在這里找到所有字符串並將所有這些字符串放入列表中。 然后,我將創建一個唯一查詢列表,然后在使用count方法查找計數之后。
input.txt
shoes
memory card
earphones
led bulb
mobile
earphones
led bulb
mobile
上面是我的輸入文件。
new = []
with open("input.txt") as inf:
for line in inf:
line = line.strip("\n")
new.append(line)
unique = list(set(new))
for i in unique:
cnt = new.count(i)
print i,cnt
和輸出應如下所示:
mobile 2
memory card 1
led bulb 2
shoes 1
earphones 2
您可以使用計數器:
from collections import Counter
with open("input.txt") as inf:
c = Counter(l.strip() for l in inf)
給出:
Counter({'led bulb': 2, 'earphones': 2, 'mobile': 2, 'memory card': 1, 'shoes': 1})
要么
for k,v in c.items():
print(k,v)
這使:
memory card 1
mobile 2
earphones 2
led bulb 2
shoes 1
更好的方法是使用字典對它們進行計數:
count = {}
for L in open("input.txt"):
count[L] = count.get(L, 0) + 1
最終得到一本從行到其各自計數的字典。
count
方法之所以快速是因為它是用C語言實現的,但是仍然必須掃描每個唯一字符串的完整列表,因此您的實現是O(n ^ 2)(考慮使所有字符串都分開的最壞情況)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.