Python Foundation Nineth Day-Iteration object, iterator object, generator, ternary expression list resolution, builder expression

Source: Internet
Author: User
Tags iterable

Chicken soup:

Always instill in yourself a thought: TMD is an individual, and what will he do and I will not? Will the king have a better feeling? I admit that people have a talent difference, but diligence can make up for defects! Therefore, according to the above points of view, as long as the birth is not a fool, then there is no stupid person, only lazy pig! As long as diligence and progress, small white will become big God. Come on

--run, little white.

One, iteration object, iterator object1. Iteration

Definition: An iterative object with the __iter__ method

Python's common data types are iterative objects, in addition to numbers.

Example: Using Isinstance to determine whether Python's common data type is an iterative object, it is verified that Python's common data types are iterative objects in addition to the numeric types.

From collections import  Iterableint1 = 1STR1 = ' Xiaobai ' List1 = [1,2,3,4,5]tuple1 = (1,2,3,4,5) Dic1 = {' A ': 1, ' B ': 2, ' C ' : 3}set1 = {1,2,3,4}f = open (' A.txt ', ' W ') # Use Isinstance to determine if it is an iterative object print (Isinstance (int1,iterable))   # Numeric type result: Falseprint (Isinstance (str1,iterable))   # string Result: Trueprint (Isinstance (list1,iterable))  # List results: Trueprint (isinstance (tuple1,iterable)) # tuple Result: Trueprint (isinstance)   # Dictionary result: dic1,iterable ( Isinstance (set1,iterable)   # Collection Result: Trueprint (Isinstance (f,iterable))      # file Result: True

Output Result:

Falsetruetruetruetruetruetrue
View Code

2. Iterators

Definition: The iterator is the result of iterating over the __iter__ of the iteration object and then executing the parentheses.

Value: The Iterator object passes the __next__ method, plus parentheses to the value in the iterator. (Iterators also have a __iter__ method.) )

Characteristics:

Pros: not dependent on indexes, lazy computing saves memory

Disadvantage: The value is not convenient, one-time value, can only live after take, can not be returned.

Example 1: The iterator is evaluated in the way of __next__ ()

L = [1,2,3,4,5]x = l.__iter__ () # iterator print (x.__next__ ()) print (x.__next__ ()) Print (  x.__next__ ()) Print (x.__next__ ( ) Print (x.__next__ ()) print (x.__next__ ())  # known list L has 5 values,                    # is an exception when you take the 6th value stopiteration

Output Result:

1Traceback (most recent):2  "c:/users/william/pycharmprojects/python_ item2/study/day9/iterator. Py" in <module>34    print(x.__next__())  #  known list L has 5 values,5stopiteration
View Code

Example 2: Using Isinstance to determine whether a Python common data type is an iterator object

From collections import  Iteratorint1 = 1STR1 = ' Xiaobai ' List1 = [1,2,3,4,5]tuple1 = (1,2,3,4,5) Dic1 = {' A ': 1, ' B ': 2, ' C ' : 3}set1 = {1,2,3,4}f = open (' A.txt ', ' W ') # Use Isinstance to determine if the iterator object is print (Isinstance (int1,iterator))   # Numeric type result: Falseprint (Isinstance (Str1,iterator))   # string Result: Trueprint (Isinstance (List1,iterator))  # List results: Trueprint (isinstance (Tuple1,iterator)) # tuple Result: Trueprint (isinstance)   # Dictionary result: Dic1,iterator ( Isinstance (Set1,iterator)   # Collection Result: Trueprint (Isinstance (F,iterator))      # file Result: True

Output Result:

Falsefalsefalsefalsefalsefalsetrue
View Code

Example 3: The iterator executes the __iter__ method and gets itself.

# file is iterator with open (' A.txt ', ' R ', encoding= ' utf-8 ') as F:    print (f)                        # get iterator    obj = f.__iter__ ()             # Execute __iter__ After the iterator is still    print (obj is f)               # True

Output Result:

<_io. Textiowrapper name='a.txt' mode='r' encoding='  utf-8'>True
View Code

3. For loop principle

Steps:

1. Execute the __iter__ () method of the iterative object first to get the iterator

2, the For loop automatically calls the __next__ () method within the iterator, and assigns the resulting return value to the variable

3. Until the stopiteration is caught, the loop ends again.

the For loop can only determine whether the object being traversed is an iterative object , and not just whether it is an iterator.

Cases:

L = [1,2,3,4]for i in L:  #  1, first execute the __iter__ () method of the Iteration object, get the iterator             # 2, the For loop will automatically call the iterator below the __next__ () method, get the return value and then assign the variable "i"             # 3, until the stopiteration exception is reported, the for loop then snaps to this exception, and finally ends the loop.    Print (i)

4. Use the while loop to implement a value that does not depend on the index. (1) try...except

A new point of knowledge is used here:

Try...except

Used to catch exceptions that occur with the program.

Grammar:

Try

Logic

Except the exception to catch:

Conditions

(2) Use the while loop to implement a value that does not depend on the index
D = {' A ': 1, ' B ': 2, ' C ': 3}obj = d.__iter__ ()      # 1, the Iteration object is first converted to an iterator while True:             # 2, then the value of the __next__ () method    try:                # 3, use try...except to catch stopiteration anomaly.        i = obj.__next__ ()        print (i)    except stopiteration:        break

Second, generator

Python Foundation Nineth Day-Iteration object, iterator object, generator, ternary expression list resolution, builder expression

Related Article

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.