趙斌 — APRIL 29, 2015 在 python 代碼中能夠看到一些常見的 trick,在這裏作一個簡單的小結。python
##json 字符串格式化 在開發 web 應用的時候常常會用到 json 字符串,可是一段比較長的 json 字符串是可讀性較差的,不容易看出來裏面結構的。 這時候就能夠用 python 來把 json 字符串漂亮的打印出來。web
root@Exp-1:/tmp# cat json.txt {"menu": {"breakfast": {"English Muffin": {"price": 7.5}, "Bread Basket": {"price": 20, "desc": "Assortment of fresh baked fruit breads and muffins"}, "Fruit Breads": {"price": 8}}, "drink": {"Hot Tea": {"price": 5}, "Juice": {"price": 10, "type": ["apple", "watermelon", "orange"]}}}} root@Exp-1:/tmp# root@Exp-1:/tmp# cat json.txt | python -m json.tool { "menu": { "breakfast": { "Bread Basket": { "desc": "Assortment of fresh baked fruit breads and muffins", "price": 20 }, "English Muffin": { "price": 7.5 }, "Fruit Breads": { "price": 8 } }, "drink": { "Hot Tea": { "price": 5 }, "Juice": { "price": 10, "type": [ "apple", "watermelon", "orange" ] } } } } root@Exp-1:/tmp#
##else 的妙用 在某些場景下咱們須要判斷咱們是不是從一個 for
循環中 break
跳出來的,而且只針對 break
跳出的狀況作相應的處理。這時候咱們一般的作法是使用一個 flag
變量來標識是不是從 for
循環中跳出的。 以下面的這個例子,查看在 60 到 80 之間是否存在 17 的倍數。json
flag = False for item in xrange(60, 80): if item % 17 == 0: flag = True break if flag: print "Exists at least one number can be divided by 17"
其實這時候能夠使用 else
在不引入新變量的狀況下達到一樣的效果數據結構
for item in xrange(60, 80): if item % 17 == 0: flag = True break else: print "exist"
##setdefault 方法 dictionary
是 python
一個很強大的內置數據結構,可是使用起來仍是有不方便的地方,好比在多層嵌套的時候咱們一般會這麼寫app
dyna_routes = {} method = 'GET' whole_rule = None # 一些其餘的邏輯處理 ... if method in dyna_routes: dyna_routes[method].append(whole_rule) else: dyna_routes[method] = [whole_rule]
其實還有一種更簡單的寫法能夠達到一樣的效果ide
self.dyna_routes.setdefault(method, []).append(whole_rule)ui
或者能夠使用 `collections.defaultdict` 模塊code
import collections dyna_routes = collections.defaultdict(list) ... dyna_routes[method].append(whole_rule)