Python 程式可查詢特定字串中的每個字元的出現次數
在本文中,我們將瞭解如何解決下述問題。
問題陳述 − 我們已有一個字串,我們需要找出特定字串中每個字元出現的次數。
這裡我們將討論 3 種方法,如下所述:L
方法 1 − 暴力法
示例
test_str = "Tutorialspoint"
#count dictionary
count_dict = {}
for i in test_str:
#for existing characters in the dictionary
if i in count_dict:
count_dict[i] += 1
#for new characters to be added
else:
count_dict[i] = 1
print ("Count of all characters in Tutorialspoint is :\n "+
str(count_dict))輸出
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}方法 2 − 使用 collections 模組
示例
from collections import Counter
test_str = "Tutorialspoint"
# using collections.Counter() we generate a dictionary
res = Counter(test_str)
print ("Count of all characters in Tutorialspoint is :\n "+
str(dict(res)))輸出
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}方法 3 − 在 lambda 表示式中使用 set()
示例
test_str = "Tutorialspoint"
# using set() to calculate unique characters in the given string
res = {i : test_str.count(i) for i in set(test_str)}
print ("Count of all characters in Tutorialspoint is :\n "+
str(dict(res)))輸出
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}結論
在本文中,我們已瞭解如何在特定字串中找出每個字元出現的次數。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP