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

熱線電話:13121318867

登錄
首頁精彩閱讀Python中的列表生成式與生成器學習教程
Python中的列表生成式與生成器學習教程
2018-07-30
收藏

Python中的列表生成式與生成器學習教程

這篇文章主要介紹了Python中的列表生成式與生成器學習教程,Python中的Generator生成器比列表生成式功能更為強大,需要的朋友可以參考下
列表生成式
即創(chuàng)建列表的方式,最笨的方法就是寫循環(huán)逐個生成,前面也介紹過可以使用range()函數(shù)來生成,不過只能生成線性列表,下面看看更為高級的生成方式:    
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

寫列表生成式時,把要生成的元素x * x放到前面,后面跟for循環(huán),就可以把list創(chuàng)建出來,十分有用,多寫幾次,很快就可以熟悉這種語法。
你甚至可以在后面加上if判斷:    
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

循環(huán)嵌套,全排列:    
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

看一個簡單應用,列出當前目錄下所有文件和目錄:    
>>> import os
>>> [d for d in os.listdir('.')]
['README.md', '.git', 'image', 'os', 'lib', 'sublime-imfix', 'src']

前面也說過Python里循環(huán)中可以同時引用兩個變量,所以生成變量也可以:    
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.iteritems()]
['y=B', 'x=A', 'z=C']

也可以通過一個list生成另一個list,例如把一個list中所有字符串變?yōu)樾懀?nbsp;   
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']

但是這里有個問題,list中如果有其他非字符串類型,那么lower()會報錯,解決辦法:    
>>> L = ['Hello', 'World', 'IBM', 'Apple', 12, 34]
>>> [s.lower() if isinstance(s,str) else s for s in L]
['hello', 'world', 'ibm', 'apple', 12, 34]

此外,列表生成式還有許多神奇用法,說明請看注釋:    
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
 
list(range(1, 11))
 
# 生成1乘1,2乘2...10乘10
L = []
for x in range(1, 11):
  L.append(x * x)
 
# 上面太麻煩,看下面
[x * x for x in range(1, 11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
 
# 加上if,就可以篩選出僅偶數(shù)的平方
[x * x for x in range(1, 11) if x % 2 == 0]
# [4, 16, 36, 64, 100]
 
# 兩層循環(huán),可以生成全排列
[m + n for m in 'ABC' for n in 'XYZ']
# ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
 
# 列出當前目錄下的所有文件和目錄名
import os
[d for d in os.listdir('.')] # on.listdir可以列出文件和目錄
 
# 列表生成式也可以使用兩個變量來生成list:
d = {'x': 'A', 'y': 'B', 'z': 'C'}
[k + '=' + v for k, v in d.items()]
# ['x=A', 'z=C', 'y=B']
 
# 把一個list中所有的字符串變成小寫
L = ['Hello', 'World', 'IBM', 'Apple']
[s.lower() for s in L]
# ['hello', 'world', 'ibm', 'apple']
 
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s, str)]
print(L2)
# ['hello', 'world', 'apple']
# isinstance函數(shù)可以判斷一個變量是不是字符串

生成器
列表生成式雖然強大,但是也會有一個問題,當我們想生成一個很大的列表時,會非常耗時,并且占用很大的存儲空間,關鍵是這里面的元素可能你只需要用到前面很少的一部分,大部分的空間和時間都浪費了。Python提供了一種邊計算邊使用的機制,稱為生成器(Generator),創(chuàng)建一個Generator最簡單的方法就是把[]改為():    
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x7fe73eb85cd0>

如果要一個一個打印出來,可以通過generator的next()方法:    
>>> g.next()
0
>>> g.next()
1
>>> g.next()
4
>>> g.next()
9
>>> g.next()
16
>>> g.next()
25
>>> g.next()
36
>>> g.next()
49
>>> g.next()
64
>>> g.next()
81
>>> g.next()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
StopIteration

其實generator object也是可迭代的,所以可以用循環(huán)打印,還不會報錯。    
>>> g = (x * x for x in range(10))
>>> for n in g:
...   print n
...

這是簡單的推算算法,但是如果算法比較復雜,寫在()里就不太合適了,我們可以換一種方式,使用函數(shù)來實現(xiàn)。
比如,著名的斐波拉契數(shù)列(Fibonacci),除第一個和第二個數(shù)外,任意一個數(shù)都可由前兩個數(shù)相加得到:
1, 1, 2, 3, 5, 8, 13, 21, 34, …
斐波拉契數(shù)列用列表生成式寫不出來,但是,用函數(shù)把它打印出來卻很容易:    
def fib(max):
  n, a, b = 0, 0, 1
  while n < max:
    print b
    a, b = b, a + b
    n = n + 1

上面的函數(shù)可以輸出斐波那契數(shù)列的前N個數(shù),這個也是通過前面的數(shù)推算出后面的,所以可以把函數(shù)變成generator object,只需要把print b改為yield b即可。    
def fib(max):
  n, a, b = 0, 0, 1
  while n < max:
    yield b
    a, b = b, a + b
    n = n + 1

如果一個函數(shù)定義中包含了yield關鍵字,這個函數(shù)就不在是普通函數(shù),而是一個generator object。    
>>> fib(6)
<generator object fib at 0x7fa1c3fcdaf0>
>>> fib(6).next()
1

所以要想調用這個函數(shù),需要使用next()函數(shù),并且遇到y(tǒng)ield語句返回(可以把yield理解為return):    
def odd():
  print 'step 1'
  yield 1
  print 'step 2'
  yield 3
  print 'step 3'
  yield 5

看看調用輸出結果:
    
>>> o = odd()
>>> o.next()
step 1
1
>>> o.next()
step 2
3
>>> o.next()
step 3
5
>>> o.next()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
StopIteration

同樣也可以改為for循環(huán)語句輸出。例如:    
def odd():
  print 'step 1'
  yield 1
  print 'step 2'
  yield 2
  print 'step 3'
  yield 3
 
if __name__ == '__main__':
  o = odd()
  while True:
    try:
      print o.next()
    except:
      break

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

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

數(shù)據(jù)分析師考試動態(tài)
數(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(); // 調用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調,回調的第一個參數(shù)驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 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); }