小编典典

什么比“不”更“ pythonic”

python

我已经看到了两种方式,但是哪种方式更适合Python?

a = [1, 2, 3]

# version 1
if not 4 in a:
    print 'is the not more pythonic?'

# version 2
if 4 not in a:
    print 'this haz more engrish'

哪种方法被认为是更好的Python?


阅读 232

收藏
2020-12-20

共1个答案

小编典典

第二个选项是Pythonic,原因有两个:

  • 它是 一个 运算符,转换为一个字节码操作数。另一行是真的not (4 in a); 两个操作员。

碰巧的是,Python会 优化
后一种情况
并转换not (x in y)x not in y任何情况,但这是CPython编译器的实现细节。

  • 这接近于您在英语中使用相同逻辑的方式。
2020-12-20