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

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀Python編碼時(shí)應(yīng)該注意的幾個(gè)情況
Python編碼時(shí)應(yīng)該注意的幾個(gè)情況
2018-06-06
收藏

Python編碼時(shí)應(yīng)該注意的幾個(gè)情況

在編程過(guò)程中,多了解語(yǔ)言周邊的一些知識(shí),以及一些技巧,可以讓你加速成為一個(gè)優(yōu)秀的程序員。
對(duì)于Python程序員,你需要注意一下本文所提到的這些事情。你也可以看看Zen of Python(Python之禪),這里面提到了一些注意事項(xiàng),并配以示例,可以幫助你快速提高。

1. 漂亮勝于丑陋

實(shí)現(xiàn)一個(gè)功能:讀取一列數(shù)據(jù),只返回偶數(shù)并除以2。下面的代碼,哪個(gè)更好一些呢?

代碼如下:
#----------------------------------------
halve_evens_only = lambda nums: map(lambda i: i/2, filter(lambda i: not i%2, nums)) 
#----------------------------------------
def halve_evens_only(nums):
   return [i/2 for i in nums if not i % 2]

2. 記住Python中非常簡(jiǎn)單的事情

代碼如下:
# 交換兩個(gè)變量
a, b = b, a
# 切片(slice)操作符中的step參數(shù)。(切片操作符在python中的原型是[start:stop:step],即:[開(kāi)始索引:結(jié)束索引:步長(zhǎng)值])
a = [1,2,3,4,5]
>>> a[::2] # 遍歷列表中增量為2的數(shù)據(jù)
[1,3,5]
# 特殊情況下,`x[::-1]`是實(shí)現(xiàn)x逆序的實(shí)用的方式
>>> a[::-1] 
[5,4,3,2,1]
# 逆序并切片
>>> x[::-1]
[5, 4, 3, 2, 1]
>>> x[::-2]
[5, 3, 1]

3. 不要使用可變對(duì)象作為默認(rèn)值

代碼如下:
def function(x, l=[]): #不要這樣

def function(x, l=None): # 好的方式
   if l is None:
      l = []

這是因?yàn)楫?dāng)def聲明被執(zhí)行時(shí),默認(rèn)參數(shù)總是被評(píng)估。

4. 使用iteritems而不是items

代碼如下:
iteritems 使用generators ,因此當(dāng)通過(guò)非常大的列表進(jìn)行迭代時(shí),iteritems 更好一些。
d = {1: "1", 2: "2", 3: "3"}
for key, val in d.items() # 當(dāng)調(diào)用時(shí)構(gòu)建完整的列表
for key, val in d.iteritems() # 當(dāng)請(qǐng)求時(shí)只調(diào)用值

5. 使用isinstance ,而不是type

代碼如下:
# 不要這樣做        
if type(s) == type(""): ...
if type(seq) == list or \
   type(seq) == tuple: ...

# 應(yīng)該這樣
if isinstance(s, basestring): ...
if isinstance(seq, (list, tuple)): ...

原因可參閱:stackoverflow

注意我使用的是basestring 而不是str,因?yàn)槿绻粋€(gè)unicode對(duì)象是字符串的話,可能會(huì)試圖進(jìn)行檢查。例如:

代碼如下:
>>> a=u'aaaa'
>>> print isinstance(a, basestring)
    True
>>> print isinstance(a, str)
    False

這是因?yàn)樵赑ython 3.0以下版本中,有兩個(gè)字符串類型str 和unicode。

6. 了解各種容器

Python有各種容器數(shù)據(jù)類型,在特定的情況下,相比內(nèi)置容器(如list 和dict ),這是更好的選擇。

我敢肯定,大部分人不使用它。我身邊一些粗心大意的人,一些可能會(huì)用下面的方式來(lái)寫(xiě)代碼。

代碼如下:
freqs = {}
for c in "abracadabra":
    try:
        freqs[c] += 1
    except:
        freqs[c] = 1

也有人會(huì)說(shuō)下面是一個(gè)更好的解決方案:

代碼如下:
freqs = {}
  for c in "abracadabra":
      freqs[c] = freqs.get(c, 0) + 1

更確切來(lái)說(shuō),應(yīng)該使用collection 類型defaultdict。

代碼如下:
from collections import defaultdict
freqs = defaultdict(int)
for c in "abracadabra":
    freqs[c] += 1

其他容器:
namedtuple()    # 工廠函數(shù),用于創(chuàng)建帶命名字段的元組子類 
deque           # 類似列表的容器,允許任意端快速附加和取出 
Counter   # dict子類,用于哈希對(duì)象計(jì)數(shù) 
OrderedDict   # dict子類,用于存儲(chǔ)添加的命令記錄 
defaultdict   # dict子類,用于調(diào)用工廠函數(shù),以補(bǔ)充缺失的值

7. Python中創(chuàng)建類的魔術(shù)方法(magic methods)

    __eq__(self, other)      # 定義 == 運(yùn)算符的行為 
    __ne__(self, other)      # 定義 != 運(yùn)算符的行為 
    __lt__(self, other)      # 定義 < 運(yùn)算符的行為 
    __gt__(self, other)      # 定義 > 運(yùn)算符的行為 
    __le__(self, other)      # 定義 <= 運(yùn)算符的行為 
    __ge__(self, other)      # 定義 >= 運(yùn)算符的行為

8. 必要時(shí)使用Ellipsis(省略號(hào)“...”)

Ellipsis 是用來(lái)對(duì)高維數(shù)據(jù)結(jié)構(gòu)進(jìn)行切片的。作為切片(:)插入,來(lái)擴(kuò)展多維切片到所有的維度。例如:

代碼如下:

>>> from numpy import arange
    >>> a = arange(16).reshape(2,2,2,2)

    # 現(xiàn)在,有了一個(gè)4維矩陣2x2x2x2,如果選擇4維矩陣中所有的首元素,你可以使用ellipsis符號(hào)。

    >>> a[..., 0].flatten()
    array([ 0, 2, 4, 6, 8, 10, 12, 14])

    # 這相當(dāng)于
    >>> a[:,:,:,0].flatten()
    array([ 0, 2, 4, 6, 8, 10, 12, 14])

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

若不方便掃碼,搜微信號(hào):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(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".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 = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+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); }