文字列のリストを維持し、リストにある場合はさまざまな変数をチェックし続けたいと思います。
私がやっていることは:
li=[one,two,three]
for x in different_x_values:
if(x in li):
print 'yes'
x in li
ある文字列が他の文字列のコレクションにあるかどうかをチェックするよりも速い方法はありますか?
文字列のリストを維持し、リストにある場合はさまざまな変数をチェックし続けたいと思います。
私がやっていることは:
li=[one,two,three]
for x in different_x_values:
if(x in li):
print 'yes'
x in li
ある文字列が他の文字列のコレクションにあるかどうかをチェックするよりも速い方法はありますか?
最近のPythonバージョンに組み込まれている「set()」データ型を確認してください。リストよりも高速であるはずです。以前は辞書キーが高速でしたが、現在はセットが同等かそれ以上高速であると思います。したがって、2.5より前のバージョンのPythonを使用している場合は、次のようにすることができます(辞書は):
li = {'one':1, 'two': 1, 'three':1}
for x in different_values:
if x in li:
print 'yes'
最近のバージョンでは、liをset()にするだけです。
set
これにはオブジェクトを使用します。
Python2> s = set(["one", "two", "three"])
Python2> "one" in s
True
Python2> s2 = set(["three", "four", "five"])
交差点:
Python2> s & s2
set(['three'])
Python2> x = "three"
Python2> x in s & s2
True
それがあなたが望むものだと思います。2つのセットの交差点です。また、セットオブジェクトについて知っていれば、インテントの方が読みやすいと思います。
print set(different_values).intersection(li)
同じように動作するはずです...より速いかもしれません。
>>> other_values = ["franks","pies","pie","beans"]
>>> li = ["apple","pie","franks","and","beans"]
>>> set(other_values).intersection(li)
set(['franks', 'beans', 'pie'])
ここにいくつかのベンチマークがあります
In [1]: other_values = range(1000)
In [2]: li = range(500,1000)
In [3]: %timeit set(other_values).intersection(li)
10000 loops, best of 3: 78.6 us per loop
In [4]: %timeit [x for x in other_values if x in li]
100 loops, best of 3: 8.7 ms per loop
In [5]: %timeit set(other_values) & set(li)
10000 loops, best of 3: 97.6 us per loop
設定された交差点が非常に高速であるように見えます
あなたはすでにあなたの答えを得ていると確信しています、これは完全を期すためです。好奇心から、私は次の結果を得た前述の方法のテストを実行しました。
サイズ=メインリストのサイズ
setopttime:s1&s2を使用するもの
setintersectiontime:交差演算を使用するもの
bruteforcetime:burte force time
サイズ=
1000setoptime:0:00:00.001000
setintersectiontime:0:00:00.001000
bruteforcetime:0:00:00.005000
サイズ=
10000setoptime:0:00:00.001000
setintersectiontime:0:00:00.010000
bruteforcetime:0:00:00.367000
サイズ=
100000setoptime:0:00:00.001000
setintersectiontime:0:00:00.115000
bruteforcetime:0:00:35.444000
方法1(setopttime)が勝ちます。確認したい場合のコードは次のとおりです。
import timeit
import datetime
def getList(size):
s=[]
for i in range(size):
s.append(str(i))
return s
def getSubList(size):
s=[]
for i in range(size/2):
s.append(str(i))
return s
def testSet(size):
s=set(getList(size))
sublist=set(getSubList(size))
list(s&sublist)
def testIntersection(size):
s=set(getList(size))
sublist=set(getSubList(size))
list(s.intersection(sublist))
def bruteForce(size):
s=getList(size)
sublist=getSubList(size)
final=[]
for elem in sublist:
try:
if s.index(elem)!=-1:
final.append(elem)
except ValueError:
pass
currentsize=1000
for i in range(3):
t1=datetime.datetime.now()
testSet(1000)
t2=datetime.datetime.now()
testIntersection(currentsize)
t3=datetime.datetime.now()
bruteForce(currentsize)
t4=datetime.datetime.now()
print "Size="+str(currentsize)
print "setoptime:"+str(t2-t1)
print "setintersectiontime:"+str(t3-t2)
print "bruteforcetime:"+str(t4-t3)
currentsize=currentsize*10