99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python中的一些陷阱與技巧小結(jié)
Python中的一些陷阱與技巧小結(jié)
2017-12-08
收藏

Python中的一些陷阱與技巧小結(jié)

Python是一種被廣泛使用的強大語言,讓我們深入這種語言,并且學(xué)習一些控制語句的技巧,標準庫的竅門和一些常見的陷阱。
Python(和它的各種庫)非常龐大。它被用于系統(tǒng)自動化、web應(yīng)用、大數(shù)據(jù)、數(shù)據(jù)分析及安全軟件。這篇文件旨在展示一些知之甚少的技巧,這些技巧將帶領(lǐng)你走上一條開發(fā)速度更快、調(diào)試更容易并且充滿趣味的道路。
學(xué)習Python和學(xué)習所有其他語言一樣,真正有用的資源不是各個語言繁瑣的超大官方文檔,而是使用常用語法、庫和Python社區(qū)共享知識的能力。
探索標準數(shù)據(jù)類型
謙遜的enumerate

遍歷在Python中非常簡單,使用“for foo in bar:”就可以。    
drinks = ["coffee", "tea", "milk", "water"]
for drink in drinks:
  print("thirsty for", drink)
#thirsty for coffee
#thirsty for tea
#thirsty for milk
#thirsty for water

但是同時使用元素的序號和元素本身也是常見的需求。我們經(jīng)常看到一些程序員使用len()和range()來通過下標迭代列表,但是有一種更簡單的方式。    
drinks = ["coffee", "tea", "milk", "water"]
for index, drink in enumerate(drinks):
  print("Item {} is {}".format(index, drink))
#Item 0 is coffee
#Item 1 is tea
#Item 2 is milk
#Item 3 is water

enumerate 函數(shù)可以同時遍歷元素及其序號。
Set類型

許多概念都可以歸結(jié)到對集合(set)的操作。例如:確認一個列表沒有重復(fù)的元素;查看兩個列表共同的元素等等。Python提供了set數(shù)據(jù)類型以使類似這樣的操作更快捷更具可讀性。    
# deduplicate a list *fast*
print(set(["ham", "eggs", "bacon", "ham"]))
# {'bacon', 'eggs', 'ham'}
 
# compare lists to find differences/similarities
# {} without "key":"value" pairs makes a set
menu = {"pancakes", "ham", "eggs", "bacon"}
new_menu = {"coffee", "ham", "eggs", "bacon", "bagels"}
 
new_items = new_menu.difference(menu)
print("Try our new", ", ".join(new_items))
# Try our new bagels, coffee
 
discontinued_items = menu.difference(new_menu)
print("Sorry, we no longer have", ", ".join(discontinued_items))
# Sorry, we no longer have pancakes
 
old_items = new_menu.intersection(menu)
print("Or get the same old", ", ".join(old_items))
# Or get the same old eggs, bacon, ham
 
full_menu = new_menu.union(menu)
print("At one time or another, we've served:", ", ".join(full_menu))
# At one time or another, we've served: coffee, ham, pancakes, bagels, bacon, eggs

intersection 函數(shù)比較列表中所有元素,返回兩個集合的交集。在我們的例子中,早餐的主食為bacon、eggs和ham。
collections.namedtuple

如果你不想給一個類添加方法,但又想使用foo.prop的調(diào)用方式,那么你需要的就是namedtuple。你提前定義好類屬性,然后就可以實例化一個輕量級的類,這樣的方式會比完整的對象占用更少的內(nèi)存。    
LightObject = namedtuple('LightObject', ['shortname', 'otherprop'])
m = LightObject()
m.shortname = 'athing'
> Traceback (most recent call last):
> AttributeError: can't set attribute

用這種方式你無法設(shè)置namedtuple的屬性,正如你不能修改元組(tuple)中元素的值。你需要在實例化namedtuple的時候設(shè)置屬性的值。    
LightObject = namedtuple('LightObject', ['shortname', 'otherprop'])
n = LightObject(shortname='something', otherprop='something else')
n.shortname
# something
collections.defaultdict

在寫Python應(yīng)用使用字典時,很多時候有些關(guān)鍵字一開始并不存在,例如下面的例子。
    
login_times = {}
for t in logins:
  if login_times.get(t.username, None):
    login_times[t.username].append(t.datetime)
  else:
    login_times[t.username] = [t.datetime]

使用defaultdict 我們可以跳過檢查關(guān)鍵字是否存在的邏輯,對某個未定義key的任意訪問,都會返回一個空列表(或者其他數(shù)據(jù)類型)。    
login_times = collections.defaultdict(list)
for t in logins:
  login_times[t.username].append(t.datetime)

你甚至可以使用自定義的類,這樣調(diào)用的時候?qū)嵗粋€類。    
from datetime import datetime
class Event(object):
  def __init__(self, t=None):
  if t is None:
    self.time = datetime.now()
  else:
    self.time = t
 
events = collections.defaultdict(Event)
 
for e in user_events:
  print(events[e.name].time)

如果既想具有defaultdict的特性,同時還想用訪問屬性的方式來處理嵌套的key,那么可以了解一下 addict。    
normal_dict = {
  'a': {
    'b': {
      'c': {
        'd': {
          'e': 'really really nested dict'
        }
      }
    }
  }
}
 
from addict import Dict
addicted = Dict()
addicted.a.b.c.d.e = 'really really nested'
print(addicted)
# {'a': {'b': {'c': {'d': {'e': 'really really nested'}}}}}

這段小程序比標準的dict要容易寫的多。那么為什么不用defaultdict呢? 它看起來也夠簡單了。    
from collections import defaultdict
default = defaultdict(dict)
default['a']['b']['c']['d']['e'] = 'really really nested dict'
# fails

這段代碼看起來沒什么問題,但是它最終拋出了KeyError異常。這是因為default[‘a(chǎn)']是dict,不是defaultdict.讓我們構(gòu)造一個value是defaulted dictionaries類型的defaultdict,這樣也只能解決兩級嵌套。

如果你只是需要一個默認計數(shù)器,你可以使用collection.Counter,這個類提供了許多方便的函數(shù),例如 most_common.
控制流

當學(xué)習Python中的控制結(jié)構(gòu)時,通常要認真學(xué)習 for, while,if-elif-else, 和 try-except。只要正確使用,這幾個控制結(jié)構(gòu)能夠處理絕大多數(shù)的情況。也是基于這個原因,幾乎你所遇到的所有語言都提供類似的控制結(jié)構(gòu)語句。在基本的控制結(jié)構(gòu)以外,Python也額外提供一些不常用的控制結(jié)構(gòu),這些結(jié)構(gòu)會使你的代碼更具可讀性和可維護性。
Great Exceptations

Exceptions作為一種控制結(jié)構(gòu),在處理數(shù)據(jù)庫、sockets、文件或者任何可能失敗的資源時非常常用。使用標準的 try 、except 結(jié)構(gòu)寫數(shù)據(jù)庫操作時通常是類型這樣的方式。    
try:
   
# get API data
  data = db.find(id='foo')
# may raise exception
   
# manipulate the data
  db.add(data)
   
# save it again
  db.commit()
# may raise exception
except Exception:
   
# log the failure
  db.rollback()
 
db.close()

你能發(fā)現(xiàn)這里的問題嗎?這里有兩種可能的異常會觸發(fā)相同的except模塊。這意味著查找數(shù)據(jù)失敗(或者為查詢數(shù)據(jù)建立連接失?。l(fā)回退操作。這絕對不是我們想要的,因為在這個時間點上事務(wù)并沒有開始。同樣回退也不應(yīng)該是數(shù)據(jù)庫連接失敗的正確響應(yīng),因此讓我們將不同的情況分開處理。

首先,我們將處理查詢數(shù)據(jù)。    
try:
   
# get API data
  data = db.find(id='foo')
# may raise exception
except Exception:
   
# log the failure and bail out
  log.warn("Could not retrieve FOO")
  return
 
# manipulate the data
db.add(data)

現(xiàn)在數(shù)據(jù)檢索擁有自己的try-except,這樣當我們沒有取得數(shù)據(jù)時,我們可以采取任何處理方式。沒有數(shù)據(jù)我們的代碼不大可能再做有用的事,因此我們將僅僅退出函數(shù)。除了退出你也可以構(gòu)造一個默認對象,重新進行檢索或者結(jié)束整個程序。

現(xiàn)在讓我們將commit的代碼也單獨包起來,這樣它也能更優(yōu)雅的進行錯誤處理。    
try:
  db.commit()
# may raise exception
except Exception:
  log.warn("Failure committing transaction, rolling back")
  db.rollback()
else:
  log.info("Saved the new FOO")
finally:
  db.close()

實際上,我們已經(jīng)增加了兩端代碼。首先,讓我們看看else,當沒有異常發(fā)生時會執(zhí)行這里的代碼。在我們的例子中,這里只是將事務(wù)成功的信息寫入日志,但是你可以按照需要進行更多有趣的操作。一種可能的應(yīng)用是啟動后臺任務(wù)或者通知。

很明顯finally 子句在這里的作用是保證db.close() 總是能夠運行。回顧一下,我們可以看到所有和數(shù)據(jù)存儲相關(guān)的代碼最終都在相同的縮進級別中形成了漂亮的邏輯分組。以后需要進行代碼維護時,將很直觀的看出這幾行代碼都是用于完成 commit操作的。
Context and Control

之前,我們已經(jīng)看到使用異常來進行處理控制流。通常,基本步驟如下:

        嘗試獲取資源(文件、網(wǎng)絡(luò)連接等)
        如果失敗,清除留下的所有東西
        成功獲得資源則進行相應(yīng)操作
        寫日志
        程序結(jié)束

考慮到這一點,讓我們再看一下上一章數(shù)據(jù)庫的例子。我們使用try-except-finally來保證任何我們開始的事務(wù)要么提交要么回退。    
try:
   
# attempt to acquire a resource
  db.commit()
except Exception:
   
# If it fails, clean up anything left behind
  log.warn("Failure committing transaction, rolling back")
  db.rollback()
else:
   
# If it works, perform actions
   
# In this case, we just log success
  log.info("Saved the new FOO")
finally:
   
# Clean up
  db.close()
# Program complete

我們前面的例子幾乎精確的映射到剛剛提到的步驟。這個邏輯變化的多嗎?并不多。

差不多每次存儲數(shù)據(jù),我們都將做相同的步驟。我們可以將這些邏輯寫入一個方法中,或者我們可以使用上下文管理器(context manager)    
db = db_library.connect("fakesql://")
# as a function
commit_or_rollback(db)
 
# context manager
with transaction("fakesql://") as db:
   
# retrieve data here
   
# modify data here

上下文管理器通過設(shè)置代碼段運行時需要的資源(上下文環(huán)境)來保護代碼段。在我們的例子中,我們需要處理一個數(shù)據(jù)庫事務(wù),那么過程將是這樣的:

        連接數(shù)據(jù)庫
        在代碼段的開頭開始操作
        在代碼段的結(jié)尾提交或者回滾
        在代碼段的結(jié)尾清除資源

讓我們建立一個上下文管理器,使用上下文管理器為我們隱藏數(shù)據(jù)庫的設(shè)置工作。contextmanager 的接口非常簡單。上下文管理器的對象需要具有一個__enter__()方法用來設(shè)置所需的上下文環(huán)境,還需要一個__exit__(exc_type, exc_val, exc_tb) 方法在離開代碼段之后調(diào)用。如果沒有異常,那么三個 exc_* 參數(shù)將都是None。

此處的__enter__方法非常簡單,我們先從這個函數(shù)開始    
class DatabaseTransaction(object):
  def __init__(self, connection_info):
    self.conn = db_library.connect(connection_info)
 
  def __enter__(self):
    return self.conn

__enter__方法只是返回數(shù)據(jù)庫連接,在代碼段內(nèi)我們使用這個數(shù)據(jù)庫連接來存取數(shù)據(jù)。數(shù)據(jù)庫連接實際上是在__init__ 方法中建立的,因此如果數(shù)據(jù)庫建立連接失敗,那么代碼段將不會執(zhí)行。

現(xiàn)在讓我們定義事務(wù)將如何在 __exit__ 方法中完成。這里面要做的工作就比較多了,因為這里要處理代碼段中所有的異常并且還要完成事務(wù)的關(guān)閉工作。
    
def __exit__(self, exc_type, exc_val, exc_tb):
    if exc_type is not None:
      self.conn.rollback()
 
    try:
      self.conn.commit()
    except Exception:
      self.conn.rollback()
    finally:
      self.conn.close()

現(xiàn)在我們就可以使用 DatabaseTransaction 類作為我們例子中的上下文管理器了。在類內(nèi)部, __enter__ 和 __exit__ 方法將開始和設(shè)置數(shù)據(jù)連接并且處理善后工作。    
# context manager
with DatabaseTransaction("fakesql://") as db:
   
# retrieve data here
   
# modify data here

為了改進我們的(簡單)事務(wù)管理器,我們可以添加各種異常處理。即使是現(xiàn)在的樣子,這個事務(wù)管理器已經(jīng)為我們隱藏了許多復(fù)雜的處理,這樣你不用每次從數(shù)據(jù)庫拉取數(shù)據(jù)時都要擔心與數(shù)據(jù)庫相關(guān)的細節(jié)。
生成器

Python 2中引入的生成器(generators)是一種實現(xiàn)迭代的簡單方式,這種方式不會一次產(chǎn)生所有的值。Python中典型的函數(shù)行為是開始執(zhí)行,然后進行一些操作,最后返回結(jié)果(或者不返回)。

生成器的行為卻不是這樣的。    
def my_generator(v):
  yield 'first ' + v
  yield 'second ' + v
  yield 'third ' + v
 
print(my_generator('thing'))
# <generator object my_generator at 0x....>

使用 yield 關(guān)鍵字代替 return ,這就是生成器的獨特之處。當我們調(diào)用 my_generator('thing') 時,我得到的不是函數(shù)的結(jié)果而是一個生成器對象,這個生成器對象可以在任何我們使用列表或其他可迭代對象的地方使用。

更常見的用法是像下面例子那樣將生成器作為循環(huán)的一部分。循環(huán)會一直進行,直到生成器停止 yield值。    
for value in my_generator('thing'):
  print value
 
# first thing
# second thing
# third thing
 
gen = my_generator('thing')
next(gen)
# 'first thing'
next(gen)
# 'second thing'
next(gen)
# 'third thing'
next(gen)
# raises StopIteration exception

生成器實例化之后不做任何事直到被要求產(chǎn)生數(shù)值,這時它將一直執(zhí)行到遇到第一個 yield 并且將這個值返回給調(diào)用者,然后生成器保存上下文環(huán)境后掛起一直到調(diào)用者需要下一個值。

現(xiàn)在我們來寫一個比剛才返回三個硬編碼的值更有用的生成器。經(jīng)典的生成器例子是一個無窮的斐波納契數(shù)列生成器,我們來試一試。數(shù)列從1開始,依次返回前兩個數(shù)之和。    
def fib_generator():
  a = 0
  b = 1
  while True:
    yield a
    a, b = b, a + b

函數(shù)中的 while True 循環(huán)通常情況下應(yīng)該避免使用,因為這會導(dǎo)致函數(shù)無法返回,但是對于生成器卻無所謂,只要保證循環(huán)中有 yield 。我們在使用這種生成器的時候要注意添加結(jié)束條件,因該生成器可以持續(xù)不斷的返回數(shù)值。

現(xiàn)在,使用我們的生成器來計算第一個大于10000的斐波納契數(shù)列值。    
min = 10000
for number in fib_generator():
  if number > min:
    print(number, "is the first fibonacci number over", min)
    break

這非常簡單,我們可以把數(shù)值定的任意大,代碼最終都會產(chǎn)生斐波納契數(shù)列中第一個大于X的值。

讓我們看一個更實際的例子。翻頁接口是應(yīng)對應(yīng)用限制和避免向移動設(shè)備發(fā)送大于50兆JSON數(shù)據(jù)包的一種常見方法。首先,我們定義需要的API,然后我們?yōu)樗鼘懸粋€生成器在我們的代碼中隱藏翻頁邏輯。

我們使用的API來自Scream,這是一個用戶討論他們吃過的或想吃的餐廳的地方。他們的搜索API非常簡單,基本是下面這樣。    
GET http://scream-about-food.com/search?q=coffee
{
  "results": [
    {"name": "Coffee Spot",
     "screams": 99
    },
    {"name": "Corner Coffee",
     "screams": 403
    },
    {"name": "Coffee Moose",
     "screams": 31
    },
    {...}
  ]
  "more": true,
  "_next": "http://scream-about-food.com/search?q=coffee?p=2"
}

他們將下一頁的鏈接嵌入到API應(yīng)答中,這樣當需要獲得下一頁時就非常簡單了。我們能夠不考慮頁碼,只是獲取第一頁。為了獲得數(shù)據(jù),我們將使用常見的 requests 庫,并且用生成器將其封裝以展示我們的搜索結(jié)果。

這個生成器將處理分頁并且限制重試邏輯,它將按照下述邏輯工作:

        收到要搜索的內(nèi)容
        查詢scream-about-food接口
        如果接口失敗進行重試
        一次yield一個結(jié)果
        如果有的話,獲取下一頁
        當沒有更多結(jié)果時,退出

非常簡單。我來實現(xiàn)這個生成器,為了簡化代碼我們暫時不考慮重試邏輯。    
import requests
 
api_url = "http://scream-about-food.com/search?q={term}"
 
def infinite_search(term):
  url = api_url.format(term)
  while True:
    data = requests.get(url).json()
 
    for place in data['results']:
      yield place
 
     
# end if we've gone through all the results
    if not data['more']: break
 
    url = data['_next']

當我們創(chuàng)建了生成器,你只需要傳入搜索的內(nèi)容,然后生成器將會生成請求,如果結(jié)果存在則獲取結(jié)果。當然這里有些未處理的邊界問題。異常沒有處理,當API失敗或者返回了無法識別的JSON,生成器將拋出異常。

盡管存在這些未處理完善的地方,我們?nèi)匀荒苁褂眠@些代碼獲得我們的餐廳在關(guān)鍵字“coffee”搜索結(jié)果中的排序。    
# pass a number to start at as the second argument if you don't want
# zero-indexing
for number, result in enumerate(infinite_search("coffee"), 1):
  if result['name'] == "The Coffee Stain":
    print("Our restaurant, The Coffee Stain is number ", number)
    return
print("Our restaurant, The Coffee Stain didnt't show up at all! :(")

如果使用Python 3,當你使用標準庫時你也能使用生成器。調(diào)用類似 dict.items() 這樣的函數(shù)時,不返回列表而是返回生成器。在Python 2中為了獲得這種行為,Python 2中添加了 dict.iteritems() 函數(shù),但是用的比較少。
Python 2 and 3 compatibility

從Python 2 遷移到Python 3對任何代碼庫(或者開發(fā)人員)都是一項艱巨的任務(wù),但是寫出兩個版本都能運行的代碼也是可能的。Python 2.7將被支持到2020年,但是許多新的特性將不支持向后兼容。目前,如果你還不能完全放棄Python 2, 那最好使用Python 2.7 和 3+兼容的特性。

對于兩個版本支持特性的全面指引,可以在python.org上看 Porting Python 2 Code 。

讓我們查看一下在打算寫兼容代碼時,你將遇到的最常見的情況,以及如何使用 __future__ 作為變通方案。
print or print()

幾乎每一個從Python 2 切換到Python 3的開發(fā)者都會寫出錯誤的print 表達式。幸運的是,你能夠通過導(dǎo)入 print_function 模塊,將print作為一個函數(shù)而不是一個關(guān)鍵字來寫出可兼容的print.    
for result in infinite_search("coffee"):
  if result['name'] == "The Coffee Stain":
    print("Our restaurant, The Coffee Stain is number ", result['number'])
    return
print("Our restaurant, The Coffee Stain didn't show up at all! :(")
Divided Over Division

從Python 2 到 Python 3,除法的默認行為也發(fā)生了變化。在Python 2中,整數(shù)的除法只進行整除,小數(shù)部分全部截去。大多數(shù)用戶不希望這樣的行為,因此在Python 3中即使是整數(shù)之間的除法也執(zhí)行浮點除。    
print "hello"
# Python 2
print("hello")
# Python 3
 
from __future__ import print_function
print("hello")
# Python 2
print("hello")
# Python 3

這種行為的改變會導(dǎo)致編寫同時運行在Python 2 和 Python 3上的代碼時,帶來一連串的小bug。我們再一次需要 __future__ 模塊。導(dǎo)入 division 將使代碼在兩個版本中產(chǎn)生相同的運行結(jié)果。    
print(1 / 3)
# Python 2
# 0
print(1 / 3)
# Python 3
# 0.3333333333333333
print(1 // 3)
# Python 3
# 0

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }