0

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 unsubscriptableelem[0]

それで、どうすればこれを処理できますか?try : exceptブロックを使用する必要がありますか、それとも別の方法がありますか?

4

5 に答える 5

2

Try ... except を使用すると、コードを柔軟に操作できます。これは良いアイデアです。

このドキュメントのpython例外処理を確認してください

例外処理には、「従来の」エラー管理手法に比べて次の利点があります。

エラー処理コードを「通常の」コードから 分離すると、プログラム コードの通常の論理フローから異常なことが起こったときに何をすべきかの詳細を分離する方法が提供されます。 エラーを呼び出しスタックに伝播 することで、より高いレベルで修正アクションを実行できます。これにより、エラーが発生したメソッドを呼び出すメソッドで修正アクションを実行できます。 エラータイプとエラーの区別をグループ化 すると、例外処理に同様の階層構造を作成できるため、論理的な方法でグループ化できます。

ほんの一例:

def count_occurrences(p,letter):
    count = 0
    for elem in p:
        try:    # Put you code which can throw exception in try Block
            if elem[0]==letter:
                count = count+1
        except Exception, ex: # You can catch specific exceptions if you want over here
              print ex.message  # Handle your exception here
              #raise   # The 'raise' statement with no arguments inside an error
                       # handler tells Python to re-raise the exception with the 
                       # original traceback intact

    return count
于 2012-07-02T07:04:07.717 に答える
1

関数から何を求めるかを決定する必要があります。

def count_occurrences(p,letter):
    count = 0
    for elem in p:
        if isinstance(elem, basestring):
            if elem[0]==letter:
                count = count+1
        else:
            # you could do something else here or just ignore it, but it seems
            # that your function really needs a list of strings as argument 
            # so it would be an error to call it with anything else and it should 
            # not fail silently.
            raise TypeError("String expected")
    return count
  • タイプに一致しない要素を無視することもできます。その場合else、上記の例で -section を空白のままにします。
  • 文字列のリストのみを引数として受け入れたい。その場合、上記の例は完全にあなたのものであり、無効な型が渡された場合でもエラーが発生します。

詳細については、Python のドキュメントを参照してくださいisinstance

ただし、ループの外側の補足try-exceptブロックでは、パフォーマンスが向上する可能性があります。

于 2012-07-02T07:06:12.660 に答える
1

次のタイプをチェックするisinstance()条件を条件に追加します。ifelem

def count_occurrences(p,letter):
    count = 0
    for elem in p:
        if isinstance(elem,str) and elem[0]==letter: #if the first condition is true then
                                                     # only it'll check the next condition
            count = count+1
    return count
于 2012-07-02T07:23:34.537 に答える
0

より効果的に次のように記述されます:

sum(1 for i in sequence if i.startswith('d')) # or for single char i[0] == 'd'

無効なタイプの場合は、try / exceptionを使用して操作を失敗させるか、適切なタイプのみを除外することができます。例:

sum(1 for i in sequence if isinstance(i, basestring) and i[0] == 'd')

または、リストが同種である必要があるために失敗を処理するには、次のようにします。

   try:
       return sum(1 for i in sequence if i[0] =='d')
   except TypeError as e:
       pass # type doesn't have subscripting
   except IndexError as e:
       pass # may or may not be a str, but len() == 0

等...

ちなみに、str.startswith('d')を使用しても発生しないため、''.startswith('d')Falseを返します。

于 2012-07-02T07:14:26.193 に答える
0

を使用しない場合は、次のtry ... exceptようにすることができます。

if isinstance(elem[0],int): 
 { ... }

そのようにして、おそらく、その要素を「スキップ」できます。

より良い解決策はisinstance、正しいタイプでテストし、「テスト失敗」の場合は要素をスキップすることです。

そう

if isinstance(elem,str) and elem[0]==letter:
 {...}
于 2012-07-02T07:04:04.627 に答える