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

时间:2012-08-15 14:35:12

标签: 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代替==

的测试

1 个答案:

答案 0 :(得分:6)

不,没有。通常不需要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())