自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python構(gòu)造列表基本應(yīng)用語法詳解

開發(fā) 后端
我們今天將會通過這篇文章中的一段代碼示例的解讀來為大家詳細(xì)介紹一下Python構(gòu)造列表的語法應(yīng)用方式,希望可以給大家?guī)硪恍椭?/div>

Python編程語言中有許多應(yīng)用方式和其他我們所熟悉的預(yù)言有很大的不同之處。不過這一語言的主要特點就在于簡單易用,所以想學(xué)習(xí)起來并不困難。我們在這里可以先來一起了解一下Python構(gòu)造列表的相關(guān)語法。

Python構(gòu)造列表語法代碼示例:

  1. #!/usr/bin/env python  
  2. # -*- coding: GBK -*-  
  3. import urllib  
  4. from sgmllib import SGMLParser  
  5. class URLLister(SGMLParser):  
  6. def reset(self):  
  7. SGMLParser.reset(self)  
  8. self.urls = []  
  9. def start_a(self, attrs):  
  10. href = [v for k, v in attrs if k == 'href']  
  11. if href:  
  12. self.urls.extend(href)  
  13. url = r'http://www.sinc.sunysb.edu/Clubs/buddhism/
    JinGangJingShuoShenMo/'
     
  14. sock = urllib.urlopen(url)  
  15. htmlSource = sock.read()  
  16. sock.close()  
  17. #print htmlSource  
  18. f = file('jingangjing.html', 'w')  
  19. f.write(htmlSource)  
  20. f.close()  
  21. mypath = r'http://www.sinc.sunysb.edu/Clubs/buddhism/
    JinGangJingShuoShenMo/'
     
  22. parser = URLLister()  
  23. parser.feed(htmlSource)  
  24. for url in parser.urls:  
  25. myurl = mypath + url  
  26. print "get: " + myurl  
  27. sock2 = urllib.urlopen(myurl)  
  28. html2 = sock2.read()  
  29. sock2.close()  
  30. # 保存到文件  
  31. print "save as: " + url  
  32. f2 = file(url, 'w')  
  33. f2.write(html2)  
  34. f2.close() 

[] 的語法是 python 中的 list comprehension, 用于Python構(gòu)造列表。

  1. href = [v for k, v in attrs if k == 'href'] 

大致上相當(dāng)于:

  1. href = []   
  2. for k,v in attrs:   
  3. if k == 'href':   
  4. href.append(v) 

以上就是我們?yōu)榇蠹医榻B的Python構(gòu)造列表的相關(guān)語法應(yīng)用。

【編輯推薦】

  1. 利用PDB實現(xiàn)Python程序調(diào)試
  2. Python單元測試正確使用規(guī)則
  3. Python SQLITE數(shù)據(jù)庫操作簡便易用
  4. 編寫Python程序?qū)崿F(xiàn)行數(shù)統(tǒng)計
  5. Python print正確使用方法淺析
責(zé)任編輯:曹凱 來源: 博客園
相關(guān)推薦

2010-03-03 16:08:26

Python取得文件列

2013-12-12 16:10:21

Lua腳本語言

2010-03-03 16:40:55

Python HTTP

2010-03-04 14:57:08

Python解密VBS

2010-03-03 14:30:05

Python set類

2010-03-03 14:40:37

Python打包方法

2010-03-04 09:27:34

調(diào)用Python腳本

2010-03-03 10:03:55

Python連接Sql

2010-07-08 15:24:17

SNMP trap

2010-03-05 15:47:59

Python Stri

2010-03-03 15:17:46

Python調(diào)用MyS

2010-02-04 17:16:33

C++調(diào)用python

2010-03-03 13:32:08

Python壓縮文件

2010-02-25 10:52:29

WCF響應(yīng)服務(wù)

2010-02-26 13:40:28

WCF消息頭

2010-02-02 14:45:35

C++ typeof

2009-12-09 09:22:45

PHP常用語法

2010-02-25 18:04:02

WCF IIS宿主

2010-03-01 15:40:04

WCF實例停用

2010-03-01 11:24:31

WCF面向服務(wù)
點贊
收藏

51CTO技術(shù)棧公眾號