什么是'不'的'pythonic' [英] What is more 'pythonic' for 'not'

查看:105
本文介绍了什么是'不'的'pythonic'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过两种方式,但哪种方式更像Pythonic?

I have seen it both ways, but which way is more 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'

将考虑哪种方式更好的Python?

Which way would be considered better Python?

推荐答案

第二个选项更多Pythonic有两个原因:

The second option is more Pythonic for two reasons:


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

  • It is one operator, translating to one bytecode operand. The other line is really not (4 in a); two operators.

碰巧, Python 优化后一种情况并将 not(x in y)转换为 x而不是y无论如何,,但这是CPython编译器的一个实现细节。

As it happens, Python optimizes the latter case and translates not (x in y) into x not in y anyway, but that is an implementation detail of the CPython compiler.

这篇关于什么是'不'的'pythonic'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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