对于内置的 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
运算符通常不需要维护 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())
关于python - python 列表是否具有用于测试身份的 __contains__ 的等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11971286/