リストからアイテムを取得するための標準的なアプローチはありますが、範囲外のデフォルト値を返しますか?
例として、私は今このような関数を持っています (まあ、これの多くの変種、私の最新のものは CSV ファイルを読むためのものです):
def list_get_def( lst, ndx, def_val ):
if ndx >= len(lst):
return def_val
return lst[ndx]
リストからアイテムを取得するための標準的なアプローチはありますが、範囲外のデフォルト値を返しますか?
例として、私は今このような関数を持っています (まあ、これの多くの変種、私の最新のものは CSV ファイルを読むためのものです):
def list_get_def( lst, ndx, def_val ):
if ndx >= len(lst):
return def_val
return lst[ndx]
ブロックを使用しtry-except
てキャッチしIndexError
ます。
>>> def testFunc(lst, index):
try:
return lst[index]
except IndexError:
return "abc"
>>> testFunc([1, 2, 3], 2)
3
>>> testFunc([1, 2, 3], 9)
'abc'
同様の質問hereget
では、辞書のようにリストにメソッドがない理由について説明しています。
if
本当にステートメントを使用したい場合は、コードを 1 行だけ使用して実行できます。
>>> def testFunc(lst, index):
return lst[index] if index < len(lst) else "abc"
>>> testFunc([1, 2, 3], 2)
3
>>> testFunc([1, 2, 3], 9)
'abc'
リストの getimtem を上書きしたくない場合は、dict have のような get メソッドを記述できます。
class fancyList_if(list):
def get(self, index, default = None):
if (index > len(self)):
return default
return self.__getitem__(index)
範囲外になることをめったに期待しない場合は、これを exce として実装できます。
class fancyList_except(list):
def get(self, index, default = None):
try:
self.__getitem__(index)
except IndexError:
return default
ベンチマーク:
In [58]: a = fancyList_if((1,3,4,5))
In [59]: b = fancyList_except((1,3,4,5))
In [60]: %timeit a.get(2, 10)
1000000 loops, best of 3: 494 ns per loop
In [61]: %timeit a.get(10, 10)
1000000 loops, best of 3: 305 ns per loop
In [62]: %timeit b.get(2, 10)
1000000 loops, best of 3: 409 ns per loop
In [63]: %timeit b.get(10, 10)
1000000 loops, best of 3: 1.67 us per loop
とんとん:
500ヒット + 300ミス = 400ヒット + 1700ミス
ヒット/ミス = 14
したがって、14 回に 1 回以上のルックアップが「失敗」すると予想される場合は、if ステートメントを使用するか、try/catch を使用します。