Iterators and generators

Source: Internet
Author: User

1. Two ways to create generator

1.1 s = (x*x for x in range (10))

This way of creating print S is:

<generator Object <genexpr> at 0x0000028b68b47888>

1.2

def f ():
Print ("OK")
Yield 1
Print ("Ok1") # Next logo
Yield 2
Print ("Ok2")
Return None
F ()

Both S and F () are an iterative object iteration.

Relative to the List Builder is the equivalent of finding a chef, but the dishes are not done. The list is to store all the elements in memory.

1.2next method

Next (s) can bring up the first element of S.

Next (f ())

Next (f ())

Next (f ()) # Print 3 OK no error receive with one variable
########################################
g = f ()
Next (g) # Print OK Ok1 ok2 and error Ok2 was printed see GA ()
Next (g)
Next (g)

Note that you want to receive it with a variable.

Def GA ():
Print ("OK")
Count = yield 1 # yield is equivalent to freezing the function next will be here then yield starts debug
Print (count)
Print ("Ok1")
Yield 2
b = GA ()
t = b.send (None) # equals next (b) but not directly send "Gaga" will error no value for you to assign value
Print (t)
B.send ("Gaga")
#jieguo: OK Gaga ok1
2. Iterator iterator

# generators are iterators (iterator) iterators that contain generators
L = [1,2,3,4] # Can iterate objects
D = ITER (l)
Print (d) # <list_iterator object at 0x0000016c2ae36c18>
# What is an iterator 1. There is ITER 2. There's next.
Print (Next (d))
########################################## #3
For i in [1,2,3,4]:
Print (i)
# What the For loop does
#1. Call the Iter method to return an iterator object
#2. Keep calling the next method of the object
#3. Handling Exception Stopiterator

From collections Import iterator,iterable
Print (Isinstance (l,list))
Print (Isinstance (d,iterator))

Iterators and generators

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.