[英]How to count the occurrences of a string and only print it out once?
我希望我的代码只按字母顺序输出字符串中的每个字母一次,例如banana
将输出abn
。
问题是我仍然需要它来计算字符串中每个字母的出现次数,因此输出应如下所示:
a occurs in the word banana a total of 3 times(s)
b occurs in the word banana a total of 1 time(s)
n occurs in the word banana a total of 2 time(s)
...
这是我的代码:
def letter_counter(string):
stg = string.lower()
stg = ''.join(sorted(stg))
for i in stg:
a = stg.count(i)
print(f'the letter {i} appears in the word {string} {a} times')
letter_counter('banana')
当前输出如下:
the letter a appears in the word banana 3 times
the letter a appears in the word banana 3 times
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
the letter n appears in the word banana 2 times
您可以使用Counter
轻松地为您计算字母:
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
对于独特的字母,您可以尝试使用 set()。 所以类似for i in sorted(set(stg)):
删除重复项的技巧是使它成为一个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
后的一行移动。 set
是无序的,因此原始排序顺序丢失。 再次排序,就在循环之前,将其排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.