python程序員前輩:總結Python編程中三條常用的技巧

這篇文章主要介紹了總結Python編程中三條常用的技巧,包括JSON格式的轉換、else語句的活用和setdefault方法的使用,需要的朋友可以參考下
在 python 代碼中可以看到一些常見的 trick,在這裏做一個簡單的小結。
json 字符串格式化

在開發 web 應用的時候經常會用到 json 字符串,但是一段比較長的 json 字符串是可讀性較差的,不容易看出來裏面結構的。 這時候就可以用 python 來把 json 字符串漂亮的打印出來。

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 的倍數。

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 一個很強大的內置數據結構,但是使用起來還是有不方便的地方,比如在多層嵌套的時候我們通常會這麼寫

dyna_routes = {}
method = 'GET'
whole_rule = None
# 一些其他的邏輯處理
...
if method in dyna_routes:
  dyna_routes[method].append(whole_rule)
else:
  dyna_routes[method] = [whole_rule]

其實還有一種更簡單的寫法可以達到同樣的效果

self.dyna_routes.setdefault(method, []).append(whole_rule)

或者可以使用 collections.defaultdict 模塊

import collections
dyna_routes = collections.defaultdict(list)
...
dyna_routes[method].append(whole_rule)

推薦我們的Python學習扣qun:913066266 ,看看前輩們是如何學習的!從基礎的python腳本到web開發、爬蟲、django、數據挖掘等【PDF,實戰源碼】,零基礎到項目實戰的資料都有整理。送給每一位python的小夥伴!每天都有大牛定時講解Python技術,分享一些學習的方法和需要注意的小細節,點擊加入我們的 python學習者聚集地

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章