9

对于内置的 python 容器(list,tuple等),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

不,没有。is只是不需要经常使用运算符来证明必须维护 C 优化方法并增加 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 回答