如果loop:“x not in” vs.“not x in” [英] If loop: "x not in" vs. "not x in"

查看:132
本文介绍了如果loop:“x not in” vs.“not x in”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到这两个都是一样的:

I've noticed that both of these work the same:

如果x不在列表中如果不是列表中的x

在某些情况下两者之间是否存在某种差异?是否有理由同时拥有这两者,或者只是因为某些人写一个或另一个更自然?

Is there some sort of difference between the two in certain cases? Is there a reason for having both, or is it just because it's more natural for some people to write one or the other?

我更有可能看到哪一个其他人的代码?

Which one am I more likely to see in other people's code?

推荐答案

这两个表单生成相同的字节码,您可以清楚地验证:

The two forms make identical bytecode, as you can clearly verify:

>>> import dis
>>> dis.dis(compile('if x not in d: pass', '', 'exec'))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_NAME                1 (d)
              6 COMPARE_OP               7 (not in)
              9 JUMP_IF_FALSE            4 (to 16)
             12 POP_TOP             
             13 JUMP_FORWARD             1 (to 17)
        >>   16 POP_TOP             
        >>   17 LOAD_CONST               0 (None)
             20 RETURN_VALUE        
>>> dis.dis(compile('if not x in d: pass', '', 'exec'))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_NAME                1 (d)
              6 COMPARE_OP               7 (not in)
              9 JUMP_IF_FALSE            4 (to 16)
             12 POP_TOP             
             13 JUMP_FORWARD             1 (to 17)
        >>   16 POP_TOP             
        >>   17 LOAD_CONST               0 (None)
             20 RETURN_VALUE        

因此显然它们在语义上是相同的。

so obviously they're semantically identical.

作为一种风格问题, PEP 8 没有提到这个问题。

As a matter of style, PEP 8 does not mention the issue.

就个人而言,如果x不在y >表格 - 立即清楚不在中是一个单一的运算符,读起来像英语。 如果没有x 可能会误导某些读者认为这意味着如果(不是x)在y 中,请稍微读一下不像英语,绝对没有补偿优势。

Personally, I strongly prefer the if x not in y form -- that makes it immediately clear that not in is a single operator, and "reads like English". if not x in y may mislead some readers into thinking it means if (not x) in y, reads a bit less like English, and has absolutely no compensating advantages.

这篇关于如果loop:“x not in” vs.“not x in”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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