使用 count() 函数的字符频率字典
Character frequency dictionary using count() function
我需要一个函数的帮助,该函数将接受一个字符串和 return 一个字典,其中每个字母在字符串中出现了多少次使用 count() 函数
例如,对于“0010101”,它return是一个字典说:
The character frequency of "0010101" is {'0': 4, '1': 3}
def character_frequency(string):
if len(string) == 0:
return "{}"
# insert loop to determine the character counts in the string here
#test code for reference
tests = ["", "0010101", "aaabbb"]
for x in tests:
print('The character frequency of "' + x + '" is', character_frequency(x))
如果需要使用count()函数:
def character_frequency(string):
return {char: string.count(char) for char in set(string)}
如果您愿意接受与 count
不同的实现,一种方法是使用 get,默认值为 0:
def character_frequency(string):
freq = {}
for c in string:
freq[c] = freq.get(c, 0) + 1
return freq
#test code for reference
tests = ["", "0010101", "aaabbb"]
for x in tests:
print('The character frequency of "' + x + '" is', character_frequency(x))
输出:
The character frequency of "" is {}
The character frequency of "0010101" is {'0': 4, '1': 3}
The character frequency of "aaabbb" is {'a': 3, 'b': 3}
txt = "I love apples, apple are my favorite fruit"
print(dict(zip(txt,[txt.count(char) for char in txt])))
计算字符串中每个字符的出现次数,并将它们存储为列表
将上面的列表与相应的字符合并并转换为字典
我需要一个函数的帮助,该函数将接受一个字符串和 return 一个字典,其中每个字母在字符串中出现了多少次使用 count() 函数
例如,对于“0010101”,它return是一个字典说:
The character frequency of "0010101" is {'0': 4, '1': 3}
def character_frequency(string):
if len(string) == 0:
return "{}"
# insert loop to determine the character counts in the string here
#test code for reference
tests = ["", "0010101", "aaabbb"]
for x in tests:
print('The character frequency of "' + x + '" is', character_frequency(x))
如果需要使用count()函数:
def character_frequency(string):
return {char: string.count(char) for char in set(string)}
如果您愿意接受与 count
不同的实现,一种方法是使用 get,默认值为 0:
def character_frequency(string):
freq = {}
for c in string:
freq[c] = freq.get(c, 0) + 1
return freq
#test code for reference
tests = ["", "0010101", "aaabbb"]
for x in tests:
print('The character frequency of "' + x + '" is', character_frequency(x))
输出:
The character frequency of "" is {}
The character frequency of "0010101" is {'0': 4, '1': 3}
The character frequency of "aaabbb" is {'a': 3, 'b': 3}
txt = "I love apples, apple are my favorite fruit"
print(dict(zip(txt,[txt.count(char) for char in txt])))
计算字符串中每个字符的出现次数,并将它们存储为列表
将上面的列表与相应的字符合并并转换为字典