猿问

如何计算字符串的出现次数并且只打印一次?

我希望我的代码仅按字母顺序输出字符串中的每个字母一次,例如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


喵喵时光机
浏览 89回答 2
2回答

呼唤远方

您可以使用 aCounter为您轻松计算字母:from collections import Counterdef 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 timesthe letter b appears in the word banana 1 timesthe letter n appears in the word banana 2 times

梦里花落0921

删除重复项的技巧是使其成为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 timesthe letter b appears in the word banana 1 timethe letter n appears in the word banana 2 times请注意稍后从sorted一行移动。Aset是无序的,因此原始排序顺序丢失。在循环之前再次对其进行排序,将其排序。
随时随地看视频慕课网APP

相关分类

Python
我要回答