ルックアップ作業を行うには、ビッグデータ構造、より具体的には大きな辞書を使用する必要があります。
最初の私のコードは次のようなものです。
#build the dictionary
blablabla
#look up some information in the ditionary
blablabla
何度も検索する必要があるので、lookup(info)などの関数として実装することをお勧めします。
次に問題が発生します。大きな辞書をどのように処理すればよいですか。
lookup(info、dictionary)を使用して引数として渡す必要がありますか、それともmain()で辞書を初期化して、グローバル変数として使用する必要がありますか?
グローバル変数を維持するのは面倒だと思うので、最初のものはよりエレガントに見えます。しかし一方で、大きな辞書を関数に渡す効率についてはよくわかりません。それは何度も呼び出され、引数の受け渡しが非効率的である場合、それは確かに悪夢になります。
ありがとう。
編集1:
上記の2つの方法を実験しました。
これがコードの抜粋です。lookup1は、ルックアップを渡す引数を実装し、lookup2はグローバルデータ構造「big_dict」を使用します。
class CityDict():
def __init__():
self.code_dict = get_code_dict()
def get_city(city):
try:
return self.code_dict[city]
except Exception:
return None
def get_code_dict():
# initiate code dictionary from file
return code_dict
def lookup1(city, city_code_dict):
try:
return city_code_dict[city]
except Exception:
return None
def lookup2(city):
try:
return big_dict[city]
except Exception:
return None
t = time.time()
d = get_code_dict()
for i in range(0, 1000000):
lookup1(random.randint(0, 10000), d)
print "lookup1 is %f" % (time.time() - t)
t = time.time()
big_dict = get_code_dict()
for i in range(0, 1000000):
lookup2(random.randint(0, 1000))
print "lookup2 is %f" % (time.time() - t)
t = time.time()
cd = CityDict()
for i in range(0, 1000000):
cd.get_city(str(i))
print "class is %f" % (time.time() - t)
これは出力です:
lookup1は8.410885
です。lookup2は8.157661
です。 クラスは4.525721です。
したがって、2つの方法はほぼ同じであるように見えます。そうです、グローバル変数メソッドの方が少し効率的です。
Edit2:
Amberによって提案されたクラスバージョンを追加してから、効率を再度テストします。次に、結果から琥珀が正しいことがわかりました。クラスバージョンを使用する必要があります。