第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何計(jì)算字符串的出現(xiàn)次數(shù)并且只打印一次?

如何計(jì)算字符串的出現(xiàn)次數(shù)并且只打印一次?

喵喵時(shí)光機(jī) 2022-07-12 10:12:47
我希望我的代碼僅按字母順序輸出字符串中的每個(gè)字母一次,例如banana將輸出abn.問(wèn)題是我仍然需要它來(lái)計(jì)算字符串中每個(gè)字母的出現(xiàn)次數(shù),所以輸出應(yīng)該如下: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')而當(dāng)前的輸出如下: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 回答

?
呼喚遠(yuǎn)方

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊

您可以使用 aCounter為您輕松計(jì)算字母:


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


查看完整回答
反對(duì) 回復(fù) 2022-07-12
?
夢(mèng)里花落0921

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊

刪除重復(fù)項(xiàng)的技巧是使其成為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')

打印出來(lái):


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

請(qǐng)注意稍后從sorted一行移動(dòng)。Aset是無(wú)序的,因此原始排序順序丟失。在循環(huán)之前再次對(duì)其進(jìn)行排序,將其排序。


查看完整回答
反對(duì) 回復(fù) 2022-07-12
  • 2 回答
  • 0 關(guān)注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)