【发布时间】:2012-07-11 05:19:18
【问题描述】:
这可能是一个愚蠢的问题,但是查看the mapping of operators to functions 我注意到没有表达not in 运算符的函数。起初我认为这可能是因为解释器只是将其重新排序为not x in y,但is not 有一个函数,它的行为似乎与not in 完全相同。是我遗漏了什么,还是该运算符真的不存在?
这是一个非常愚蠢的例子,你可能想要这个:
def compare_iter(a,b,func):
return [func(aa,bb) for aa,bb in zip(a,b)]
my_compare=compare_iter(xx,yy,lambda x,y:x not in y) #lambda -- yuck
my_compare=map(operator.not_,compare_iter(xx,yy,operator.contains) #extra map? grr...
#it would be nice to do: my_compare=compare_iter(xx,yy,operator.not_contains)
当然,我可以为此编写自己的函数,但是你会付出效率的代价,而操作员模块可以将这段代码从 python 中推出,因此执行得更快。
【问题讨论】:
-
确实,不能将
a is not b简单地重新排序为not a is b吗? -
是否存在检查
not in可能比检查in更快的情况? -
@PaulManta 值得怀疑,因为
not in根据定义是一个详尽的搜索。 -
@JAB -- 可以。但这不是重点。关键是这里有一个不对称,这有点好笑。似乎应该有一个
not_contains函数,然后可以用来传递给其他函数或其他任何东西(而不是依赖lambda)。 -
@ColinDunklau 不一定。想想像布隆过滤器这样的事情,如果没有设置一个位,您可以确定该项目没有插入到集合中。
标签: python performance indexing