這里沒有列表推導和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!
新聞熱點
疑難解答