Python リストのチュートリアルを進めながら、特定の文字で始まる単語の出現回数をカウントする Python 関数を作成しようとしました。
def count_occurrences(p,letter):
count = 0
for elem in p:
if elem[0]==letter:
count = count+1
return count
>>>count_occurrences(['damon','jim','dennis'],'d')
2
>>>count_occurrences(['damon','jim'],'d')
1
>>>count_occurrences([],'d')
0
しかし、たとえば、間違った型を含むリストを入力すると、コード が int で呼び出されるため、[1,2,3]
がスローされます。TypeError:'int' object is unsubscriptable
elem[0]
それで、どうすればこれを処理できますか?try : except
ブロックを使用する必要がありますか、それとも別の方法がありますか?