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

熱線電話:13121318867

登錄
首頁精彩閱讀Python基礎(chǔ)學習之常見的內(nèi)建函數(shù)整理
Python基礎(chǔ)學習之常見的內(nèi)建函數(shù)整理
2017-11-17
收藏

Python基礎(chǔ)學習之常見的內(nèi)建函數(shù)整理

Python針對眾多的類型,提供了眾多的內(nèi)建函數(shù)來處理,這些內(nèi)建函數(shù)功用在于其往往可對多種類型對象進行類似的操作,即多種類型對象的共有的操作,下面話不多說了,來一看看詳細的介紹吧。
map()
map()函數(shù)接受兩個參數(shù),一個是函數(shù),一個是可迭代對象(Iterable),map將傳入的函數(shù)依次作用到可迭代對象的每一個元素,并把結(jié)果作為迭代器(Iterator)返回。

舉例說明,有一個函數(shù)f(x)=x^2 ,要把這個函數(shù)作用到一個list[1,2,3,4,5,6,7,8,9]上:

運用簡單的循環(huán)可以實現(xiàn):
    
>>> def f(x):
...  return x * x
...
L = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
 L.append(f(n))
print(L)

運用高階函數(shù)map() :    
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]

結(jié)果r是一個迭代器,迭代器是惰性序列,通過list()函數(shù)讓它把整個序列都計算出來并返回一個list。

如果要把這個list所有數(shù)字轉(zhuǎn)為字符串利用map()就簡單了:    
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']

小練習:利用map()函數(shù),把用戶輸入的不規(guī)范的英文名字變?yōu)槭鬃帜复髮懫渌懙囊?guī)范名字。輸入['adam', 'LISA', 'barT'],輸出['Adam', 'Lisa', 'Bart']    
def normalize(name):
  return name.capitalize()
 
 l1=["adam","LISA","barT"]
 l2=list(map(normalize,l1))
 print(l2)

reduce()

reduce()函數(shù)也是接受兩個參數(shù),一個是函數(shù),一個是可迭代對象,reduce將傳入的函數(shù)作用到可迭代對象的每個元素的結(jié)果做累計計算。然后將最終結(jié)果返回。

效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

舉例說明,將序列[1,2,3,4,5]變換成整數(shù)12345:    
>>> from functools import reduce
>>> def fn(x, y):
...  return x * 10 + y
...
>>> reduce(fn, [1, 2, 3, 4, 5])
12345

小練習:編寫一個prod()函數(shù),可以接受一個list并利用reduce求積:    
from functools import reduce
def pro (x,y):
  return x * y
 def prod(L):
  return reduce(pro,L)
 print(prod([1,3,5,7]))

map()和reduce()綜合練習:編寫str2float函數(shù),把字符串'123.456'轉(zhuǎn)換成浮點型123.456
    
CHAR_TO_FLOAT = {
 '0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9, '.': -1
}
def str2float(s):
 nums = map(lambda ch:CHAR_TO_FLOAT[ch],s)
 point = 0
 def to_float(f,n):
   nonlocal point
   if n==-1:
    point =1
    return f
   if point ==0:
    return f*10+n
   else:
    point =point *10
    return f + n/point
 
 return reduce(to_float,nums,0)#第三個參數(shù)0是初始值,對應(yīng)to_float中f

filter()

filter()函數(shù)用于過濾序列,filter()也接受一個函數(shù)和一個序列,filter()把傳入的函數(shù)依次作用于每個元素,然后根據(jù)返回值是True還是False決定保留還是丟棄該元素。

舉例說明,刪除list中的偶數(shù):    
def is_odd(n):
 return n % 2 == 1
 
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 結(jié)果: [1, 5, 9, 15]

小練習:用filter()求素數(shù)

計算素數(shù)的一個方法是埃氏篩法,它的算法理解起來非常簡單:

首先,列出從2開始的所有自然數(shù),構(gòu)造一個序列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取序列的第一個數(shù)2,它一定是素數(shù),然后用2把序列的2的倍數(shù)篩掉:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取新序列的第一個數(shù)3,它一定是素數(shù),然后用3把序列的3的倍數(shù)篩掉:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取新序列的第一個數(shù)5,然后用5把序列的5的倍數(shù)篩掉:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

不斷篩下去,就可以得到所有的素數(shù)。

用Python實現(xiàn)這個算法,先構(gòu)造一個從3開始的期數(shù)數(shù)列:    
def _odd_iter():
n = 1
 while True:
  n = n + 2
  yield n
#這是一個生成器,并且是一個無線序列

定義一個篩選函數(shù):
    
def _not_divisible(n):
 return lambda x: x % n > 0

定義一個生成器不斷返回下一個素數(shù):
    
def primes():
 yield 2
 it = _odd_iter() # 初始序列
 while True:
  n = next(it) # 返回序列的第一個數(shù)
  yield n
  it = filter(_not_divisible(n), it) # 構(gòu)造新序列

打印100以內(nèi)素數(shù):
    
for n in primes():
 if n < 100:
  print(n)
 else:
  break

sorted()

python內(nèi)置的sorted()函數(shù)可以對list進行排序:
    
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]

sorted()函數(shù)也是一個高階函數(shù),還可以接受一個key函數(shù)來實現(xiàn)自定義排序:    
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]

key指定的函數(shù)將作用于list的每一個元素上,并根據(jù)key函數(shù)返回的結(jié)果進行排序.

默認情況下,對字符串排序,是按照ASCII的大小比較的,由于'Z' < 'a',結(jié)果,大寫字母Z會排在小寫字母a的前面。如果想忽略大小寫可都轉(zhuǎn)換成小寫來比較:    
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']

要進行反向排序,不必改動key函數(shù),可以傳入第三個參數(shù)reverse=True:    
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']

小練習:假設(shè)我們用一組tuple表示學生名字和成績:L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 。用sorted()對上述列表分別按c成績從高到低排序:    
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_score(t):
 for i in t:
   return t[1]
L2=sorted(L,key= by_score)
print(L2)

運用匿名函數(shù)更簡潔:    
L2=sorted(L,key=lambda t:t[1])
print(L2)

總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助

數(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); }