2012-08-15 3 views
8

pythonのリストには__contains__と同等のものがありますか?内蔵Pythonのコンテナ(<code>list</code>、<code>tuple</code>など)<code>in</code>オペレータは前者の方法は、高速(およびきれい)であることを警告と<code>any(y == item for item in container)</code>と同等であるため

In [13]: container = range(10000) 
In [14]: %timeit (-1 in container) 
1000 loops, best of 3: 241 us per loop 
In [15]: %timeit any(-1 == item for item in container) 
1000 loops, best of 3: 1.2 ms per loop 

any(y is item for item in container)と同等であり?つまり、==の代わりにisを使用するテストですか?

答えて

6

いいえ、ありません。 is演算子は、C最適化メソッドを維持して、Python APIに混乱を加えなければならないことを正当化するためにしばしば必要とされるものではありません。

リストとタプルのテストでは、any(Cでもbtwでも同様)の完全な検索が行われます。ただし、テストでは、コンテナの基礎となる効率的な格納アルゴリズムが使用され、検索では予想される時間内に一定の時間がかかります。両方のセットとマッピングでは、キーは安定したハッシュを持つことになっています。ほとんどの場合、isは必要ありません。

だから、正しいスペルは次のとおりです。

# For sequences 
any(y is item for item in container) 

# For sets, short circuit first for the not-present case: 
# (note that you normally should not need this as you are supposed to rely on the hash) 
y in setcontainer and any(y is item for item in setcontainer) 

# For mappings, y is a key 
y in mapping 

# For mappings, y is a value, and you do not have a key, fall back to any 
any(y is item for item in mapping.itervalues()) 
+5

実際には、私は常にドキュメントの欠陥、それを考えられてきた方法 'list.index'と' list.count'などが効果に何かを言うこと」その値が* x *である最初の項目のリスト内のインデックスを返します。そのような項目がなければエラーです " – mgilson

+0

しかし、セットでさえ、' in'はハッシュ値をチェックします。オブジェクトは区別されます。 'a =(1,2,3); c =(1,2,3); cはaであり; s =セット([a]); cである。現在、私はこれが重要な時を考えることはできません。 – mgilson

+0

いいえ、ちょうどセットとディクテーションの 'の'演算子が* do * aスキャンを持っていないことを指摘してください。 –