python - python 列表是否具有用于测试身份的 __contains__ 的等价物?

标签 python identity containment

对于内置的 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 运算符通常不需要维护 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/

相关文章:

iOS 容器 View Controller 添加 child 的纵向 View

python - Django Rest 框架 : Register multiple serializers in ViewSet

python - 在 Django 中,如何内省(introspection)应用程序 url?

python - 在轮廓上绘制点 - Matplotlib/Python

Java Hibernate AutoIncrement Identity set ID to start 0 mySQL

jquery dom 可调整大小的可拖动遏制问题

python - 在 Python 中给参数命名是否与 kwarg 参数的坏做法相同?

arrays - Swift 数组标识 "Type does not conform to protocol ' AnyObject'"错误

Mysql 查询以一种奇怪的方式移动自动增量列

javascript - JQuery-UI 遏制 : 'parent' does not work