[英]count letter in words using Python
我正在與 Python 一起寫一個 function 這是一個例子: lettercount(['hello','it','is','me'],'i')
應該返回['it-1','is-1']
。
這是我的代碼:
def lettercount(list, letter):
result = [] #create an empty list
for word in list: #traverse through all the words in the provided list
if word not in result: #from this line I don't know what I'm really doing though
if letter in word:
wrd = "{}-".format(word).append(word.count(letter))
#tried to achieve the same format as provided but failed
result.append(wrd) #this is wrong because str doesn't have the attribute "append"
return result
有人可以給我提示這個問題嗎? 非常感謝!
問題是你構造wrd
的方式。 更改此行 -
wrd = "{}-".format(word).append(word.count(letter))
到 -
wrd = f"{word}-{word.count(letter)}"
請附言。 避免使用list
作為變量名,而是使用lst
等,因為list
在 Python 中是受保護的字。
def lettercount(lst, letter): out = [] for word in lst: cnt = sum(1 for l in word if l == letter) if cnt: out.append(f'{word}-{cnt}') return out
嘗試:
def lettercount(lst, letter):
result = []
for word in lst:
if letter in word:
result.append(word + '-' + str(word.count(letter)))
而且我不建議將變量命名為“list”,因為它是 Python 中的現有關鍵字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.