python-iterator vs generator

Objects that are directly used in for loops are called iterable objects, such as lists, dictionaries, etc.

An object that can be called by the next() function and returns the next value is called an iterator. (The next() method uses the __next__() method in python2.7).

When calling the next() method, if the iterator has no value to return, a StopIteration exception is raised.

When defining an iterator, there is a next() method and a __iter__ method:

class Fib(object):
    def __init__(self):
        self.a = 0
        self.b = 1
     def  __next__ (self):   #Note the difference between versions 2 and 3 
        self.a , self.b = self.b, self.a + self.b
         return   self.b
     def  __iter__ (self):
         return   self

Then you can instantiate the class and call the __next__() method directly:

fibs = Fib()
print(fibs.__next__())
print(fibs.__next__())
print(fibs.__next__())
print(fibs.__next__())
print(fibs.__next__())

============================
1
2
3
5
8

Another iterative method:

fibs = Fib()
for f in fibs:
    if f >1000:
        print(f)
        break
==========Results==========
1597

An object that implements the __iter__() method is iterable, and an object that implements the next method is an iterator.

The built-in function iter can get the iterator from the iterable object:

it = iter(["a","b","d","t","l"])

it.__next__()
Out[2]: 'a'

it.__next__()
Out[3]: 'b'

Use the list method to explicitly convert an iterator to a list

d = iter ([4,5,6,7 ])

ld = list(d)    # convert iterator to list

type(d)
Out[20]: list_iterator

type(ld)
Out[21]: list

ld
Out[22]: [4, 5, 6, 7]


Builder:

A function that contains a yield statement is called a generator.

ll = [[1,2],[3,4],[5,6]]
def print_list(list):
    for sublist in list:
        for i in sublist:
            yield i     ###
        print()
for num in print_list(ll):
    print (num, end=" ")

The above function prints each value in the list, note that the marker uses yield instead of print.

The biggest difference between its behavior and normal function is that it does not return a value like return. Each time a value is produced, using the yield statement, the function is frozen: that is, the function stops at that point and waits to be reawakened.

When the function is reawakened, it starts executing from the point where it stopped.

### Newline printing in python3

https://www.cnblogs.com/hwd9654/p/5707920.html

Everyone should know that the default line break after print in python,

So why don't we want to wrap, and don't want to talk about the output content and output it with a print function, we need to change the property of print's default newline,

Methods as below:

print('contents', end='!@#$%^&*')

end indicates how the print will end, the default is end = " \n " (newline)

Chestnut:

print ( " I wish you good health " )

print("")

 

print ( " I wish you good health " , end= '  ' )

print("")

Generator and list comprehension:

l = [x if x%3==0 else 0 for x in range(10)]   ##B

l
Out[30]: [0, 0, 0, 3, 0, 0, 6, 0, 0, 9]

l = (x if x%3 == 0 else 0 for x in range(10))   ##A

l.__next__()
Out[33]: 0

l.__next__()
Out[34]: 0

l.__next__()
Out[35]: 0

l.__next__()
Out[36]: 3

l.__next__()
Out[37]: 0

l.__next__()
Out[38]: 0

l.__next__()
Out[39]: 6

Replace the square brackets in a list generator with parentheses and it becomes a generator!
A generator is a function that contains the yield keyword. When it is called, the code in the function body will not be executed, but an iterator will be returned.

Every time a value is requested, the code in the generator is executed until a yield or return statement is encountered, yield means that a value should be generated. The return statement means that the generator should stop executing.

""""The generator consists of two parts: the generator function and the generator iterator. A generator function is defined using a statement, including the yield part, and the generator iterator is the return part of this function. ""

The generator method:

  • A generator can call the send method, passing a value to the yield statement. But it should be noted that when the generator uses the send method, the generator must have been called, that is, the next() method must have been run.
def repeater(value): #define    a generator 
    while True:
        new = (yield value)
        if new is not None:
            value = new
            

r = repeater(42)         #Instance a generator object 
r. __next__ ()             #First call , execute the generator 
Out[42]: 42


r.send( " I love LFY " )     # #Pass the value to the generator 
Out[43]: ' I love LFY '

s = repeater(56)         #Instance another generator s.send 
( " wxz " )            #Then call the send method directly and report an error! Traceback (most recent call last):


  File "<ipython-input-46-52ebe91b67e9>", line 1, in <module>
    s.send("wxz")

TypeError: can't send non-None value to a just-started generator   

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324683754&siteId=291194637