python运算符,没有“不在”的运算符 [英] python operator, no operator for "not in"

查看:127
本文介绍了python运算符,没有“不在”的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个可能很愚蠢的问题,但请查看映射运算符到函数我注意到没有函数表示不在运算符中。起初我以为这可能是因为解释器只是将它重新排序为而不是x ,但是的函数不是这似乎应该与完全相同,而不是。我错过了什么,或者该运算符确实不存在?

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)

当然我可以为此编写自己的函数,但是你需要付出高效的代价,而运算符模块可以将这些代码从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.

推荐答案

这里不需要另一个函数。不在中是<$ c的反函数$ c> in ,所以你有以下映射:

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)

你说得对,这与不一致是 / 不是,因为身份测试应该是对称的。这可能是一个设计工件。

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

这篇关于python运算符,没有“不在”的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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