1樓:Shreck Ye
其實因為字符集是已知而且連續的,直接按字元編碼對映到乙個記憶體陣列裡面效率要比字典更高。
不過既然是Python,變數都是用字典存的,效率似乎就無所謂了,更重要的是怎麼寫更簡單更快。這裡用字典也更方便簡單,參照高讚答案用collections.Counter一行就可以解決更好。
2樓:2gua
Counter的答案已經有了。
來個中規中矩的:
from
collections
import
defaultdict
import
typing
defcnt(s
:str
)->typing
.Dict
[str
,int
]:df
=defaultdict
(int
)forcin
s:df[
c]+=1
return
dict(df
)cm=cnt
("Good Better Best"
)print(cm)
3樓:satanson
統計一行:
echo ... |perl -aF -lne 'foreach(@F)++};print join "\n",map"} keys %h'
統計整片檔案:
cat file |perl -aF -lne 'foreach(@F)++}}"} keys %h'
4樓:賈湖圖
用Counter,其實就是個字典
from
collections
import
Counter
defcount(s
):dic
=Counter(s
)fork,
vindic.
items
():print("
{}\t{}"
.format(k
,v))#測試
str1
="aaabbbbcddddddaa"
count
(str1)
5樓:黃哥
解決這個問題,基本上利用字典。換乙個程式語言也是用Hash table,也叫雜湊表,所以沒有用Python特有的 collections.Counter。
C語言,用陣列定義乙個字串,那這個字串是怎麼儲存在這個陣列中的呢?
the gc 對於scanf的 s的解釋如下 Matches a sequence of non white space characters the nextpointer must be a pointer to the initial element of acharacter array t...
python中,乙個字串內有多次出現的 a ,如何用找到第n個 a 的位置?
酒罈壇兒 defindex str1 char,n 獲取指定字串中第n個指定字元在字串中的下標 param str1 指定字串 param char 指定字元 param n 個數 return 下標,如果找不到返回None location None count 0 forx inrange le...
python語言中如何判斷乙個字串有多少位?
Python2的str 編碼後的字串,在C中就是char 直接用len 查的長度便是位元組數 Python3的str 可能是UTF 16或UTF 32編碼的字串,在C中是wchar t 通常不要關心它的編碼,而抽象理解為編碼前的字串。所佔位元組數是len 的長度乘以編譯Python所用的編譯器的wc...