亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何計算字符串的出現次數并且只打印一次?

如何計算字符串的出現次數并且只打印一次?

喵喵時光機 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 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號