这里没有列表推导和lambda函数。虽然这两个用法都是Python式的,效率高也非常酷,但由于经常在StackOverflow或其他地方碰到,所以学Python的应该都知道这两个东西。同时也没有三元运算符、装饰器和生成器,因为我很少用到。
本文还有一个IPython notebook nbviewer版本。
1. 在Python 2中使用Python 3式的输出
Python 2与Python 3不兼容,这让我不知道该选择哪个版本的Python。最终我选择了Python 2,因为当时许多我需要用的库都与Python 3不兼容。
但实际上,日常使用中最大的版本差异是输出(print)和除法行为。现在我在Python 2的代码中都用import from future来导入Python 3的输出和除法。现在我用到的几乎所有库都支持Python 3,因此会很快迁移到Python 3中。
mynumber = 5 print "Python 2:"print "The number is %d" % (mynumber)print mynumber / 2,print mynumber // 2 from __future__ import print_functionfrom __future__ import division print('nPython 3:')print("The number is {}".format(mynumber))print(mynumber / 2, end=' ')print(mynumber // 2) Python 2:The number is 52 2 Python 3:The number is 52.5 2
对了,对于C系的那些更喜欢括号而不是缩进的开发者,这里还有一个彩蛋:
from __future__ import bracesFile "", line 1from __future__ import bracesSyntaxError: not a chance
2. enumerate(list)
很明显,迭代列表时,应该同时迭代其中的元素及其索引,但在很长一段时间内,我都尴尬的使用计数变量或切片。
mylist = ["It's", 'only', 'a', 'model'] for index, item in enumerate(mylist): print(index, item) 0 It's1 only2 a3 model
3. 链式比较操作符
由于我以前使用的是静态语言(在这些语言中该用法有二义性),从来没有将两个比较操作符放在一个表达式中。在许多语言中,4 > 3 > 2会返回False,因为4 > 3的结果是布尔值,而True > 2将得出False。
mynumber = 3 if 4 > mynumber > 2: print("Chained comparison operators work! n" * 3) Chained comparison operators work!Chained comparison operators work!Chained comparison operators work!
新闻热点
疑难解答