2 回答

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

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)行排序,將其排序。
添加回答
舉報(bào)