Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

performance - python operator, no operator for "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)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...