为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喵时光机 2022-07-12 10:12:47
我希望我的代码仅按字母顺序输出字符串中的每个字母一次,例如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 timesthe letter a appears in the word banana 3 timesthe 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 timesthe letter n appears in the word banana 2 times
查看完整描述

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


查看完整回答
反对 回复 2022-07-12
?
梦里花落0921

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是无序的,因此原始排序顺序丢失。在循环之前再次对其进行排序,将其排序。


查看完整回答
反对 回复 2022-07-12
  • 2 回答
  • 0 关注
  • 88 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号