在 python 代碼中可以看到一些常見的 trick,在這里做一個(gè)簡(jiǎn)單的小結(jié)。
json 字符串格式化
在開發(fā) web 應(yīng)用的時(shí)候經(jīng)常會(huì)用到 json 字符串,但是一段比較長(zhǎng)的 json 字符串是可讀性較差的,不容易看出來(lái)里面結(jié)構(gòu)的。 這時(shí)候就可以用 python 來(lái)把 json 字符串漂亮的打印出來(lái)。
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 的妙用
在某些場(chǎng)景下我們需要判斷我們是否是從一個(gè) for 循環(huán)中 break 跳出來(lái)的,并且只針對(duì) break 跳出的情況做相應(yīng)的處理。這時(shí)候我們通常的做法是使用一個(gè) flag 變量來(lái)標(biāo)識(shí)是否是從 for 循環(huán)中跳出的。 如下面的這個(gè)例子,查看在 60 到 80 之間是否存在 17 的倍數(shù)。
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"
其實(shí)這時(shí)候可以使用 else 在不引入新變量的情況下達(dá)到同樣的效果
for item in xrange(60, 80):
if item % 17 == 0:
flag = True
break
else:
print "exist"
setdefault 方法
dictionary 是 python 一個(gè)很強(qiáng)大的內(nèi)置數(shù)據(jù)結(jié)構(gòu),但是使用起來(lái)還是有不方便的地方,比如在多層嵌套的時(shí)候我們通常會(huì)這么寫
dyna_routes = {}
method = 'GET'
whole_rule = None
# 一些其他的邏輯處理
...
if method in dyna_routes:
dyna_routes[method].append(whole_rule)
else:
dyna_routes[method] = [whole_rule]
其實(shí)還有一種更簡(jiǎn)單的寫法可以達(dá)到同樣的效果
self.dyna_routes.setdefault(method, []).append(whole_rule)
或者可以使用 collections.defaultdict 模塊
import collections
dyna_routes = collections.defaultdict(list)
...
dyna_routes[method].append(whole_rule)
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

