我需要使用函数编写代码,将所有符号计数到字典中(包括空格,逗号等)和另一个函数来打印至少一次进入元组的所有元素(即给出" Hello world&#34 ;输出=(' h',' e',' l',' o','',& #39; w',' r',' d')这是我的代码到目前为止:
def frequency(word):
dict = {}
for el in word:
el = el.lower()
if el in dict and not "":
dict[el] += 1
elif el not in dict and not "":
dict[el] = 1
for k,v in dict.items():
print(k + ":" + str(v))
def different_symbols(word):
dict={}
for el in dict:
if el not in dict:
dict[el] = el
elif el in dict:
print(el)
frequency("Hello world!")
different_symbols("Hello world!")
答案 0 :(得分:2)
使用Counter.most_common()
测量频率,使用set()
测量唯一字符。如果您特别希望dict
和tuple
输入结果:
from collections import Counter
def frequency(word):
letters = Counter(word).most_common()
letters_dict = {k: v for k, v in letters}
return letters_dict
def different_symbols(word):
return tuple(set(word))
print(frequency("Hello World!"))
# {'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
print(different_symbols("Hello World!"))
# ('d', ' ', 'r', 'l', 'H', 'e', 'o', 'w') order is completely random