python列表是否有__contains__的等价物来测试身份?

Chr*_*isB 8 python identity containment

对于内置的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
Run Code Online (Sandbox Code Playgroud)

有相当于any(y is item for item in container)?也就是说,使用的测试is代替==

Mar*_*ers 6

不,没有.的is操作者只是不需要经常证明具有保持C-优化方法和添加混乱到蟒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())
Run Code Online (Sandbox Code Playgroud)

  • 事实上,我一直认为这是一个文档缺陷,方法`list.index`和`list.count`等说明效果"返回值*为*x的第一个项目列表中的索引.如果没有这样的项目则是错误的" (5认同)