Python|字符串中每个字符的频率
给定一个字符串,任务是找到该字符串中所有字符的频率,并返回一个字典,其中key
为字符, value
作为给定字符串中的频率。
方法#1:朴素的方法
只需遍历字符串并在新出现的元素的字典中形成一个键,或者如果元素已经出现,则将其值增加 1。
# Python3 code to demonstrate
# each occurrence frequency using
# naive method
# initializing string
test_str = "GeeksforGeeks"
# using naive method to get count
# of each element in string
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
# printing result
print ("Count of all characters in GeeksforGeeks is :\n "
+ str(all_freq))
输出 :
Count of all characters in GeeksforGeeks is :
{'r': 1, 'e': 4, 'k': 2, 'G': 2, 's': 2, 'f': 1, 'o': 1}
方法 #2:使用collections.Counter()
可以用来查找所有出现的最建议的方法是这种方法,这实际上得到了所有元素频率,如果需要,也可以用于打印单个元素频率。
# Python3 code to demonstrate
# each occurrence frequency using
# collections.Counter()
from collections import Counter
# initializing string
test_str = "GeeksforGeeks"
# using collections.Counter() to get
# count of each element in string
res = Counter(test_str)
# printing result
print ("Count of all characters in GeeksforGeeks is :\n "
+ str(res))
输出 :
Count of all characters in GeeksforGeeks is :
Counter({'e': 4, 's': 2, 'k': 2, 'G': 2, 'o': 1, 'r': 1, 'f': 1})
方法#3:使用dict.get()
get()
方法用于检查字符串中先前出现的字符,如果是新字符,则将 0 分配为初始字符并将 1 附加到它,否则将 1 附加到字典中该元素先前保存的值。
# Python3 code to demonstrate
# each occurrence frequency using
# dict.get()
# initializing string
test_str = "GeeksforGeeks"
# using dict.get() to get count
# of each element in string
res = {}
for keys in test_str:
res[keys] = res.get(keys, 0) + 1
# printing result
print ("Count of all characters in GeeksforGeeks is : \n"
+ str(res))
输出 :
Count of all characters in GeeksforGeeks is :
{'k': 2, 'e': 4, 's': 2, 'G': 2, 'f': 1, 'r': 1, 'o': 1}
方法 #4:使用set() + count()
count()
与set()
结合也可以完成这个任务,在这个任务中,我们只是遍历集合转换的字符串并获取原始字符串中每个字符的计数,并为该元素分配使用count()
的值。
# Python3 code to demonstrate
# each occurrence frequency using
# set() + count()
# initializing string
test_str = "GeeksforGeeks"
# using set() + count() to get count
# of each element in string
res = {i : test_str.count(i) for i in set(test_str)}
# printing result
print ("The count of all characters in GeeksforGeeks is :\n "
+ str(res))
输出 :
Count of all characters in GeeksforGeeks is :
{'G': 2, 's': 2, 'k': 2, 'e': 4, 'o': 1, 'r': 1, 'f': 1}