python 操作符,“not in"没有操作符; [英] python operator, no operator for "not in"

查看:34
本文介绍了python 操作符,“not in"没有操作符;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但看看 映射运算符到函数 我注意到没有函数可以表达 not in 运算符.起初我认为这可能是因为解释器只是将其重新排序为 not x in y,但是有一个 is not 的函数,它的行为似乎应该与与 not in 相同.是我遗漏了什么,还是那个运算符真的不存在?

This is a possibly silly question, but looking at the mapping of operators to functions I noticed that there is no function to express the not in operator. At first I thought this was probably because the interpreter just reorders this to be not x in y, but there is a function for is not which seems like it should behave exactly the same as not in. Am I missing something, or does that operator really not exist?

这是一个非常愚蠢的例子,你可能想要这个:

Here's a really stupid example where you might want this:

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)

当然,我可以为此编写自己的函数,但是你会付出效率的代价,而 operator 模块可以将这段代码从 python 中推出,因此执行得更快.

Of course I could write my own function for this, but then you pay a price in efficiency whereas the operator module could push this code out of python and therefore execute faster.

推荐答案

这里不需要另一个函数.not inin 的反函数,所以你有以下映射:

Another function is not necessary here. not in is the inverse of in, so you have the following mappings:

obj in seq => contains(seq, obj)

obj not in seq => not contains(seq, obj)

你说得对,这与 is/is not 不一致,因为身份测试应该是对称的.这可能是一个设计神器.

You are right this is not consistent with is/is not, since identity tests should be symmetrical. This might be a design artifact.

这篇关于python 操作符,“not in"没有操作符;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆