[英]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.