9

組み込みの python コンテナー ( listtuple、など) の場合、オペレーターは、前者の方法の方が高速 (かつきれい) であるという警告とin同等です。any(y == item for item in container)

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の代わりに使用するテストです。==

4

1 に答える 1

7

いいえ、ありません。isC に最適化されたメソッドを維持する必要があり、Python API に混乱をもたらすことを正当化するために、演算子は必要ありません。

inリストとタプルのテストanyは、C ではありますが、に似た完全な検索を行います。ただし、セットでは、テストはコンテナーの基礎となる効率的なストレージ アルゴリズムを利用し、予想されるケースでは検索に一定の時間がかかります。セットとマッピングの両方で、キーには安定したハッシュがあると想定されています。これは、ほとんどの場合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())
于 2012-08-15T14:38:41.027 に答える