注:這裡忽略了生成器,裝飾器,交換變數等熟知技巧
1. 函式引數unpack
老生常談的了:
1 2 3 4 5 6 7 8 |
def foo(x, y): print x, y alist = [1, 2] adict = {'x': 1, 'y': 2} foo(*alist) # 1, 2 foo(**adict) # 1, 2 |
2. 鏈式比較操作符
1 2 3 4 5 |
>>> x = 3 >>> 1 < x < 5 True >>> 4 > x >=3 True |
3. 注意函式的預設引數
1 2 3 4 5 6 7 8 |
>>> def foo(x=[]): ... x.append(1) ... print x ... >>> foo() [1] >>> foo() [1, 1] |
更安全的做法:
1 2 3 4 5 6 7 8 9 10 11 |
>>> def foo(x=None): ... if x is None: ... x = [] ... x.append(1) ... print x ... >>> foo() [1] >>> foo() [1] >>> |
4. 字典有個get()方法
dct.get(key[,default_value]), 當字典dct中找不到key時,get就會返回default_value
1 |
sum[value] = sum.get(value, 0) + 1 |
5. 帶關鍵字的格式化
1 2 3 4 |
>>> print "Hello %(name)s !" % {'name': 'James'} Hello James ! >>> print "I am years %(age)i years old" % {'age': 18} I am years 18 years old |
更新些的格式化:
1 2 |
>>> print "Hello {name} !".format(name="James") Hello James ! |
快有些模板引擎的味道了:)
6. for…else 語法
1 2 3 4 5 6 7 8 |
>>> for i in (1, 3, 5): ... if i % 2 == 0: ... break ... else: ... print "var i is always an odd" ... var i is always an odd >>> |
else語句塊會在迴圈結束後執行,除非在迴圈塊中執行break
7. dict 的特殊方法__missing__
Python 2.5之後引入的。當查詢不到key的時候,會執行這個方法。
1 2 3 4 5 6 7 8 9 10 |
>>> class Dict(dict): ... def __missing__(self, key): ... self[key] = [] ... return self[key] ... >>> dct = Dict() >>> dct["foo"].append(1) >>> dct["foo"].append(2) >>> dct["foo"] [1, 2] |
這很像collections.defaultdict不是嗎?
1 2 3 4 5 6 7 |
>>> from collections import defaultdict >>> dct = defaultdict(list) >>> dct["foo"] [] >>> dct["bar"].append("Hello") >>> dct defaultdict(<type 'list'>, {'foo': [], 'bar': ['Hello']}) |
8. 切片操作的步長引數
還能用步長-1來反轉連結串列:
1 2 3 4 5 6 |
>>> a = [1, 2, 3, 4, 5] >>> a[::2] [1, 3, 5] >>> a[::-1] [5, 4, 3, 2, 1] >>> |
9.另一種字串連線
1 2 3 |
>>> Name = "Wang" "Hong" >>> Name 'WangHong' |
連線多行:
1 2 3 4 |
>>> Name = "Wang" \ ... "Hong" >>> Name 'WangHong' |
10. Python直譯器中的”_”
1 2 3 4 |
>>> range(4) [0, 1, 2, 3] >>> _ [0, 1, 2, 3] |
_即Python直譯器上一次返回的值
11. Python 描述器
Python描述器是Python 中很魔幻的東西,方法等都是描述器。不再舉例
12. Zen
1 |
import this |
13. 巢狀列表推導式
1 2 |
>>> [(i, j) for i in range(3) for j in range(i)] [(1, 0), (2, 0), (2, 1)] |
14. try/except/else
1 2 3 4 5 6 7 8 |
try: put_4000000000_volts_through_it(parrot) except Voom: print "'E's pining!" else: print "This parrot is no more!" finally: end_sketch() |
15. print 重定向輸出到檔案
1 |
>>> print >> open("somefile", "w+"), "Hello World" |
注意開啟的模式:"w+"而不能"w", 當然"a"是可以的
16. 省略號
在Python3中你可以直接使用省略號這個文法:
1 2 3 4 5 |
Python 3.2 (r32:88445, Oct 20 2012, 14:09:50) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ... Ellipsis |
Python2 中呢?
1 2 3 4 5 6 7 |
>>> class C(object): ... def __getitem__(self, item): ... return item ... >>> C()[1:2, ..., 3] (slice(1, 2, None), Ellipsis, 3) >>> |
17. Python3中的元組unpack
真的但願Python2也這樣:
1 2 3 4 5 6 7 8 |
>>> a, b, *rest = range(10) >>> a 0 >>> b 1 >>> rest [2, 3, 4, 5, 6, 7, 8, 9] >>> |
當然也可以取出最後一個:
1 2 3 4 5 6 7 8 9 |
>>> first, second, *rest, last = range(10) >>> first 0 >>> second 1 >>> last 9 >>> rest [2, 3, 4, 5, 6, 7, 8] |
18. pow()還有第三個引數
我們都知道內建函式pow,pow(x,y)即x**y
但是它還可以有第三個引數:
1 2 3 4 |
>>> pow(4, 2, 2) 0 >>> pow(4, 2, 3) 1 |
其實第三個引數是來求模的:pow(x,y,z)?==?(x**y)?%z
注意,內建的pow和math.pow並不是一個函式,後者只接受2個引數
19. enumerate還有第二個引數
enumerate很贊,可以給我們索引和序列值的對, 但是它還有第二個引數:
1 2 3 |
>>> lst = ["a", "b", "c"] >>> list(enumerate(lst, 1)) [(1, 'a'), (2, 'b'), (3, 'c')] |
這個引數用來: 指明索引的起始值
20. 顯式的宣告一個集合
新建一個集合,我們會:
1 |
>>> set([1,2,3]) |
在Python 2.7 之後可以這麼寫了:
1 2 |
>>> {1,2,3} set([1, 2, 3]) |
21. 用切片來刪除序列的某一段
1 2 3 4 |
>>> a = [1, 2, 3, 4, 5, 6, 7] >>> a[1:4] = [] >>> a [1, 5, 6, 7] |
當然用dela[1:4]也是可以的
去除偶數項(偶數索引的):
1 2 3 4 |
>>> a = [0, 1, 2, 3, 4, 5, 6, 7] >>> del a[::2] >>> a [1, 3, 5, 7] |
22. isinstance可以接收一個元組
這個真的鮮為人知, 我們可以用isinstance(x,(float,int))來判斷x是不是數:
1 2 3 4 5 6 |
>>> isinstance(1, (float, int)) True >>> isinstance(1.3, (float, int)) True >>> isinstance("1.3", (float, int)) False |
那麼對於第三個測試,你把str加入元組就可以看到這是怎麼回事了:
1 2 |
>>> isinstance("1.3", (float, int, str)) True |
也就是那個元組裡面是或的關係,只要是其中一個的例項就返回True
23. 字典裡的無限遞迴
1 2 3 4 5 |
>>> a, b = {}, {} >>> a['b'] = b >>> b['a'] = a >>> a {'b': {'a': {...}}} |
當然你可以製作一個連結串列中的無限迴圈:
1 2 3 4 5 |
>>> a, b = [], [] >>> a.append(b) >>> b.append(a) >>> a [[[...]]] |
真心不知道有什麼用,不過蠻好玩的不是嗎
24. Python可以認識Unicode中的數字
所以說,Python很贊:
1 2 |
>>> int(u'1234') 1234 |
不只是ASCII字串的可以認出來,連Unicode的也可以。
25. 不能訪問到的屬性
回答這個答案的人太壞了:)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
>>> class O(object):pass ... >>> o = O() >>> setattr(o, "can't touch this", 123) >>> o.can't touch this File "<stdin>", line 1 o.can't touch this ^ SyntaxError: EOL while scanning string literal >>> File "<stdin>", line 1 o.can't touch this ^ SyntaxError: EOL while scanning string literal |
不過,能用setattr設定屬性,就可以用getattr取出
26. 尾語
歡迎fork, 追加內容。