Comprehensive e...LOGIN

Comprehensive example of iterators and generators

Because iterators and generators are basically interoperable, some knowledge points need to be integrated together

1. Reverse iteration

Reverse iteration, should It is also a common requirement. For example, in the example of iterating from the beginning, there is an element of the output list, from 1 to 5

list1 = [1,2,3,4,5]
for num1 in list1 :
    print ( num1 , end = ' ' )

. So what do we do from 5 to 1? This is also very simple. There is a built-in function reversed() in Python

list1 = [1,2,3,4,5]
for num1 in reversed(list1) :
    print ( num1 , end = ' ' )

Directional iteration is very simple, but one thing to note is: reverse iteration only works when the size of the object can be predetermined or the object implements __reversed__( ) to take effect. If both are not met, then you must first convert the object to a list

In fact, many times we can implement reverse iteration by implementing the __reversed__() method on a custom class. However, some knowledge points have not been mentioned in the previous chapters, but you can read them accordingly. Those with programming basics should be able to understand them after learning the above knowledge points.

# -*- coding: UTF-8 -*-
class Countdown:
    def __init__(self, start):
        self.start = start
    def __iter__(self):
    # Forward iterator
        n = self.start
        while n > 0:
            yield n
            n -= 1
    def __reversed__(self):
    # Reverse iterator
        n = 1
        while n <= self.start:
            yield n
            n += 1
for rr in reversed(Countdown(30)):
    print(rr)
for rr in Countdown(30):
    print(rr)

The output results are 1 to 30 and then 30 to 1, respectively printing in sequential order and printing in reverse order

2, iterating multiple sequences at the same time

You want to iterate through multiple sequences at the same time, taking one element from each sequence each time. Have you ever encountered such a need?

In order to iterate multiple sequences at the same time, use the zip() function. Specific example:

# -*- coding: UTF-8 -*-
names = ['laingdianshui', 'twowater', '两点水']
ages = [18, 19, 20]
for name, age in zip(names, ages):
     print(name,age)

Output results:

laingdianshui 18
twowater 19
两点水 20

In fact, zip(a, b) will generate a An iterator that returns the tuple (x, y), where x comes from a and y comes from b. Once one of the sequences reaches the end, the iteration ends. Therefore, the iteration length is consistent with the length of the shortest sequence in the parameters. Pay attention to understand this sentence, that is to say, if the lengths of a and b are inconsistent, the shortest one will be used as the standard, and the traversal will end.

Using the zip() function, we can also generate a dict (dictionary) from a key list and a value list, as follows:

# -*- coding: UTF-8 -*-
names = ['laingdianshui', 'twowater', '两点水']
ages = [18, 19, 20]
dict1= dict(zip(names,ages))
print(dict1)

Output the following results:

{'laingdianshui': 18, 'twowater': 19, '两点水': 20}

Let me mention here that zip() can accept more than two sequence parameters, not just two.

Next Section
submitReset Code
ChapterCourseware