Python4: Advanced Features

Source: Internet
Author: User
Tags generator generator

4 Advanced Features 4.1 slices [:]

  * Note:--list and tuple, string all support slicing

4.2 Iterations iteration for ... in and for ... in if

Two variable iterations,

 for inch [(1, 1), (2, 4), (3, 9)]: Results 1 1--2 4--3 9
Example 2: Dictionary >>>d={' x ': ' A ', ' y ': ' B ', ' z ': ' C '} >>> for k,v in D.items (): or [k + ' = ' + V for K, V in D.items ()] result y = B--x = A--z = C
4.3 List-generated
 for inch if  for inch ' ABC '  for inch ' XYZ ']
4.4 Generator Generator

-function: When large amounts of data are processed, one side of the loop is computed; Note: To iterate through the print element with a in loop instead of next ()
Example: Fibonacci sequence:

def= 0, 0, 1 while n < Max:yield= b, A += n + 1

Two methods are created:
1. Change from list to: Change a list-generated [] to ();
2. Change from function to: return result using yield statement instead of return statement;
  * NOTE: The yield statement returns one result at a time, in the middle of each result, suspends the state of the function so that the next time it is left to continue execution, and the generator's only note is that the generator can only traverse once
Yield image analogy: Squeeze toothpaste, from the outside every call, "squeeze" out a line, processing and then "squeeze" out of the next line, and then processing, here said the "squeeze" is yield.
About yield usage and method: https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/

Python4: Advanced Features

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.