2 回答

TA贡献1856条经验 获得超11个赞
您可以使用 aCounter为您轻松计算字母:
from collections import Counter
def letter_counter(string):
for letter, count in sorted(Counter(string.lower()).items()):
print(f'the letter {letter} appears in the word {string} {count} times')
letter_counter("banana")
给出:
the letter a appears in the word banana 3 times
the letter b appears in the word banana 1 times
the letter n appears in the word banana 2 times

TA贡献1772条经验 获得超6个赞
删除重复项的技巧是使其成为set:
def letter_counter(string):
stg = string.lower()
stg = ''.join(stg)
for i in sorted(set(stg)):
a = stg.count(i)
print(f'the letter {i} appears in the word {string} {a} time{"" if a == 1 else "s"}')
letter_counter('banana')
打印出来:
the letter a appears in the word banana 3 times
the letter b appears in the word banana 1 time
the letter n appears in the word banana 2 times
请注意稍后从sorted一行移动。Aset是无序的,因此原始排序顺序丢失。在循环之前再次对其进行排序,将其排序。
添加回答
举报