Python full stack development, DAY13 (iterator, generator)

Source: Internet
Author: User
Tags generator

One, iterator

Python all objects

Objects that can be used for loops are iterative objects

Iterative objects: Str,list,tuple,dict,set,range

Iterator: F1 file handle

Dir Prints all the action methods of the object

s = ' python ' Print (dir (s))

Execution output:

[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __ getattribute__ ', ' __getitem__ ', ' __getnewargs__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' _ _lt__ ', ' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __rmod__ ', ' __rmul__ ', ' _ _setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' capitalize ', ' casefold ', ' center ', ' count ', ' encode ', ' EndsWith ', ' expandtabs ', ' find ', ' format ', ' Format_map ', ' index ', ' isalnum ', ' isalpha ', ' isdecimal ', ' isdigit ', ' Isidentifier ', ' islower ', ' isnumeric ', ' isprintable ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' ljust ', ' lower ', ' Lstrip ' ', ' Maketrans ', ' partition ', ' replace ', ' rfind ', ' rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' Rstrip ', ' Split ', ' Splitline S ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill ']

What is an iterative object: An object that contains the __iter__ method internally is called an iterative object
An iterative object follows an iterative protocol.

How to judge two kinds of ways

The first type:

s = ' python ' Print (' __iter__ ' in Dir (s))

Execution output:

True

The second type:

From collections Import Iterablel = [1, 2, 3, 4]print (Isinstance (L, iterable))

Execution output:

True

From collections Import Iterablel = [1, 2, 3, 4]print (Type (l)) print (Isinstance (l,list))

Execution output:

<class ' list ' >
True


Type can only judge what kind of

Isinstance is more widely judged, not only judging the type, but also judging whether it can be iterated

Iterators

An iterative object can be transformed into an iterator: an object can be iterated. __ITER__ ()---> iterators
Iterators contain not only __iter__, but also __next__. follows the iterator protocol.

L1 = [1,2,3]l1_obj = l1.__iter__ ()  # iterator print (l1_obj)

Execution output:

<list_iterator Object at 0x000001987d5eb668>

Indicates that it is a list iterator object

L1 = [1,2,3]l1_obj = l1.__iter__ ()  # iterator print (' __iter__ ' in  dir (l1_obj)) #是否含有__iter__方法print (' __next__ ' in  dir (L1)) #是否含有__next__方法print (' __next__ ' in  dir (l1_obj))

Execution output:

True
False
True

From the results, it can be seen that l1_obj is an object that contains both __iter__ and __next__, so it is an iterator

Iterators use __next__ to get a value

L1 = [1,2,3]l1_obj = l1.__iter__ ()  # iterator print (l1_obj.__next__ ()) #获取一个元素print (l1_obj.__next__ ()) Print (l1_obj.__ next__ ()) print (l1_obj.__next__ ())

Execution Error:

1
Traceback (most recent):
2
3
File "e:/python_script/day13/iterator. Py", line 9, <module>
Print (l1_obj.__next__ ())
Stopiteration

If you take one more, you will get an error because the list has only 3 elements.

Use for loop mode

L1 = [1,2,3]l1_obj = l1.__iter__ ()  # Convert to iterator for I in L1_obj:    print (i)

Execution output:

1
2
3

The internal mechanism of the For loop is performed using the __next__ method. Why is there no error? It has an exception handling mechanism inside it.

Summarize:

Containing only the __iter__ method, it is the object that can iterate
that contains the __iter__ and __next__ methods is the iterator

2 Ways to Judge Iterators:

The 1th type:

L1 = [1,2,3]l1_obj = l1.__iter__ ()  # Convert to iterator print (' __iter__ ' in  dir (l1_obj))

The 2nd type:

L1 = [1,2,3]l1_obj = l1.__iter__ ()  # Convert to iterator from collections import Iteratorprint (Isinstance (L1_obj, Iterator))

Returns true, which means that it is yes

Benefits of Iterators:
1, save memory space.
2, to meet the inertia mechanism.
3, can not be repeated value, irreversible.

Irreversible, indicating that the value has been taken, cannot be taken again, it can only take the next.

for processing mechanism

L2 = [1, 2, 3, 4, 5, 6, 7, 8]for i in L2:    print (i)

1. Convert an iterative object into an iterator
2, internally using the __next__ method to take the value
3, the use of exception handling to deal with the error.

The biggest benefit of iterators is that they save memory
Good programmers will consider memory optimization, such as iterators.

Use the while loop to specify that the list be traversed with the __next__ method

L2 = [1, 2, 3, 4, 5, 6, 7, 8]l2_obj = l2.__iter__ () #1. Convert an iterative object to an iterator while True:    try:        i = l2_obj.__next__ () #内部使用__n Ext__ Method Value        print (i)    except Exception: #运用了异常处理去处理报错 break        

Try inside the code, there is an error, will not prompt red text
Exception can receive all the error, indicating the error when, how to deal with, here directly use Breck jump out of the loop

Interview questions:

Use the Whlie loop to traverse a finite object

You can use the above code directly.

Second, generator

Generator: The generator is essentially an iterator

L = [1,2,3]l.__iter__ ()

#生成器的产生方式:
1, generator function constructs.
2, generator derivation construction.
3, conversion of data type.

Python full stack development, DAY13 (iterator, generator)

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.