[英]How to count the occurrences of a string and only print it out once?
I want my code to output each letter in the string only once and in alphabetical order, for example banana
will output abn
.我希望我的代码只按字母顺序输出字符串中的每个字母一次,例如
banana
将输出abn
。
The catch is that I still need it to count the occurrences of each letter in the string, so the output should be as follows:问题是我仍然需要它来计算字符串中每个字母的出现次数,因此输出应如下所示:
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)
...
This is my code:这是我的代码:
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')
And the current output is as follows:当前输出如下:
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
You can use a Counter
to easily count the letters for you:您可以使用
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")
Gives:给出:
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
For unique letters you can try to use set().对于独特的字母,您可以尝试使用 set()。 So something like
for i in sorted(set(stg)):
所以类似
for i in sorted(set(stg)):
The trick to remove duplicates is to make it a set
:删除重复项的技巧是使它成为一个
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')
prints out:打印出来:
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
Note the move from sorted
one line later.请注意从
sorted
后的一行移动。 A set
is unordered so the original sorted order is lost. set
是无序的,因此原始排序顺序丢失。 Sorting it again, just before looping, sorts this out.再次排序,就在循环之前,将其排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.