Python loops through list elements through the iterator class (compared with yield)

Infinite iterator: loop on list elements, wrapping to first element when last element is reached

Translation: Infinite iterator: loop over the list elements, when the last element is reached, loop to the first element

Code first, analyze later

Iterator class: and use the yield method

#一 使用定义迭代器类的方法
class LoopIter:
    '''Infinite iterator: loop on list elements, wrapping to first element when last element is reached'''
    def __init__(self, l):
        self.i = 0
        self.l = l

    def __iter__(self):
        return self

    def __next__(self):
        item = self.l[self.i]
        self.i = (self.i + 1)  % len(self.l)
        return item

    def next(self):
        return self.__next__()

#二使用yield的方法
def re_list(list1):

    for i in list1:
        yield i


tem_list = [1,2,3,4,5,6]
a = LoopIter(tem_list)
b = re_list(tem_list)


for i in b:
    print(i)

print("*"*50)
for i in range(6):
    print(a.next())

Use the above code to analyze the usage scenario:

When the iterator class is used, we define an iterator class named a. We only need to call the next method in the iterator every time to loop and output the list elements.
That is, you can always use while output

When using the method defined by yield, the obtained b will stop after the list element is output and play.
Specifically, you can replace the for loop above with the code of the while loop below for verification.

while True:

    print("yield方法",next(b))

while True:
    print("迭代器类:", a.next())

Guess you like

Origin blog.csdn.net/weixin_43134049/article/details/114028858