![](/img/trans.png)
[英]How can I count the number of occurrences of a given string in a string array in pandas
[英]How can I efficiently count the number of occurrences of a given character within certain range of a string?
給定未排序的字符串,例如“ googol”。 我想在以下范圍內找到字符“ o”的出現次數:[1,3)。 因此,在這種情況下,答案將是1。
但是,我的方法的復雜度為O(N ^ 2)。 我的方法的問題是復制數組需要O(N)時間。 因此,我正在尋找另一種更有效的方法。 空間復雜性對我來說並不重要。 因為我正在學習字符串處理算法,所以最好能自己實現該算法。
任何幫助,將不勝感激。
我的方法
tmp = [0] * 26 # 26 alphabet
occurrences_table = []
tmp[ord(a_string[0])] += 1
occurrences_table.append(tmp)
for i in range(1, len(a_string)):
temp = occurrences_table[i - 1]
temp[ord(a_string[i])] += 1
occurrences_table.append(temp)
由於您不想使用計數器並想自己實現它,因此可以使用字典來整理和加速您的代碼。
a_string = "googol"
my_counter = {}
for c in a_string[:2]:
my_counter[c] = my_counter.get(c, 0) + 1
這會給你:
{'o': 1, 'g': 1}
為了進一步解釋它, a_string[:2]
使字符串中的字符一直升至索引2( 'google'[:2]
= 'go'
), for c in a_string[:2]:
遍歷這2個字符。
在下一行中, my_counter.get(c, 0) + 1
嘗試獲取鍵“ c”(字符串中的單個字符)的字典值,如果存在則返回其值,如果不存在則返回0,或者方式將增加的值添加回字典中。
編輯:
由於for循環,復雜度應僅為O(n),因為dictionary.get()
的復雜度是恆定的。
我已經對其進行了測量,對於像您這樣的非常小的字符串,此方法比Collections.Counter快8-10倍,但是對於非常大的字符串,它要慢2-3倍。
您可以使用Counter
:
from collections import Counter
a_string = "googol"
occurrences = Counter(a_string[0:2])
導致
Counter({'o': 1, 'g': 1})
注意,數組切片適用於字符串。
如果可以使用標准庫:
>>> from itertools import islice
>>> from collections import Counter
>>> Counter(islice('googol', 1, 3))
Counter({'o': 2})
>>> Counter(islice('googol', 0, 2))
Counter({'g': 1, 'o': 1})
( islice
避免使用臨時列表。)
如果要手動執行此操作:
>>> s = 'googol'
>>> counter = dict()
>>> for i in range(0, 2):
... if s[i] not in counter:
... counter[s[i]] = 1
... else:
... counter[s[i]] += 1
...
>>> counter
{'g': 1, 'o': 1}
關鍵是:使用dict
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.