Basic Application Syntax of Python constructor list

Source: Internet
Author: User

The Python programming language has many different application methods than other predictions we are familiar. However, the main feature of this language is that it is easy to use, so it is not difficult to learn. Here, we can take a look at the syntax of the Python constructor list.

Python constructor list syntax code example:

 
 
  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. # Save to file
  31. Print "save as:" + url
  32. F2 = file (url, 'w ')
  33. F2.write (html2)
  34. F2.close ()

The [] syntax is list comprehension in python, which is used to construct a list in Python.

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

Generally, it is equivalent:

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

The above is the syntax application of the Python constructor list.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.