Mic*_*ael 32 python if-statement not-operator
我已经看过两种方式,但哪种方式更像Pythonic?
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'
Run Code Online (Sandbox Code Playgroud)
哪种方式被认为是更好的Python?
Mar*_*ers 46
第二种选择是更多Pythonic,原因有两个:
它是一个运算符,转换为一个字节码操作数.另一条线确实是not (4 in a); 两个运营商.
碰巧的是,Python 优化后一种情况并转化not (x in y)为x not in y无论如何,但这是CPython编译器的实现细节.
ars*_*jii 22
大多数人都认为这4 not in a更像是Pythonic.
Python的设计目的是易于理解和理解,4 not in a听起来更像是用英语说的 - 你很可能不需要知道Python来理解这意味着什么!
请注意,就字节码而言,两者在CPython中是相同的(虽然not in在技术上是单个运算符,not 4 in a但需要进行优化):
>>> import dis
>>> def test1(a, n):
not n in a
>>> def test2(a, n):
n not in a
>>> dis.dis(test1)
2 0 LOAD_FAST 1 (n)
3 LOAD_FAST 0 (a)
6 COMPARE_OP 7 (not in)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
>>> dis.dis(test2)
2 0 LOAD_FAST 1 (n)
3 LOAD_FAST 0 (a)
6 COMPARE_OP 7 (not in)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)