This is the 10th day of my participation in the August Text Challenge.More challenges in August

1. Iterators

Iteration is one of Python’s most powerful features, as a way of accessing elements of a collection. An iterator is an object that remembers the position of the iterator. Iterator objects are accessed from the first element in the collection and can only move forward and not backward until all elements have been accessed. String, list, or tuple objects can all be used to create iterators.

What is the process of iteration? It’s a process of taking things out of the data structure in turn

(1) List derivation: can succinctly construct a new list

The usual way to construct a new list is to write it like this

Li = [] for I in range(1,10): li. Print (li)Copy the code

Output is: [1, 2, 3, 4, 5, 6, 7, 8, 9]

(2) List derivation

Li1 = [I for I in range(1,10)] print(li1)Copy the code

Output is: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Range (1,10,2) range(1,10,2)

Li3 = [I for I in range(1,10) if I % 2!=0] print(li3)Copy the code

Output: [1, 3, 5, 7, 9]

(4) How to print multiple values

Print (li4) = [(I,j) for I in range(1,5) for j in range(1,5)] print(li4)Copy the code

The output is: [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]

(5) Set derivation

Li5 = {I for I in range(1,10)} print(li5)Copy the code

Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}

(6) Dictionary derivation

Li6 = {I :j for I in range(1,10) for j in range(1,10)} print(li6)Copy the code

Output is: {1:9, 2, 9, 3, 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 9}

Small development:

Li7 = {I :j for I,j in enumerate([' sH ',' sh '])} print(li7)Copy the code

Output: {0: ‘Wu ‘, 1:’ Zhang ‘}

Note: there is no tuple derivation!!

Each loop will automatically have “iteration variable” pointing to “the next element”. (2) iterables refer to iterables (which implement __iter__), sequence types and hash types. (3) iterators refer to iterators (which implement __iter__ and __next__ methods, an iterator is an object) that can only move forward and not backward. Iterator = iter(iterable) \ next = next(iterator)

Here’s an example:

A list is an iterable. Dir looks at a list method and it has an __iter__ method inside, but a list is not an iterator. How to convert a list to an iterator

Li = [1,2,3,4] it = iterCopy the code

Gets the value of the iterator

For I in it: print(I) #Copy the code

Since it is an iterator, use the next method to get the iterator’s value — one value at a time saves space.

Next is used in two ways

Print (it.__next__()) # print(it.__next__()) # print(itCopy the code

Small expansion:…

Implementation principle of FOR

Li = [1,2,3,4] it = iter(li) try: while True: print(next(it)) except Exception as e: print(e)Copy the code

The output is 1, 2, 3, and 4

2. Generators

Thought 1: How do we implement an iterable ourselves? In a custom class, to implement the iter magic method, you must return an iterator (which you need to implement yourself). The generator

  • In Python, functions that use yield are called generators.

  • Unlike normal functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.

  • During a call generator run, each time yield is encountered, the function pauses and saves all current run information, returns the yield value, and continues from the current position on the next execution of the next() method.

  • Call a generator function that returns an iterator object.

Generator: A function that returns iterators

1. Tuple derivation

Tu = (I for I in range(1,10)) print(type(tu))Copy the code

The output is: <class ‘generator’> which means this is a generator

print(dir(tu))      			
Copy the code

Tu contains methods __iter__ and __next__, so this is an iterator

print(tu.__next__())  			
Copy the code

Since it is an iterator, it can be evaluated using the next method

Any function with a yield is a generator

Yield an object | | suspended this function is waiting for the next next reactivate

Here’s an example:

def fun(): Yield 1 # Returns a 1 and suspends the function print(' Up every day ') yield 2 # returns a 2 and suspends the function print(' Again ') Print (aa)) # print(aa) # print(bb) # print(bb) # print(bb) # print(bb) # print(bb) # print(bb) # print(bb) # print(bb) # print(bb) # print(bb) # 2 cc = next(a) # Output is: Do it again and raise StopIterationCopy the code

If print(type(fun())) prints <class ‘generator’>, this function is already a generator.

Here’s another example:

def fun(ele,n):
    count = 0
    while True:
        if count < n:
            count +=1
            yield ele
        else:
            break

a = fun('wumou',5)
for i in a:
    print(i)
Copy the code

The command output is wumou wumou wumou wumou wumou wumou

The difference between a generator and an iterator: a generator is a very simple syntax provided by Python that allows us to write our own iterators. A generator is a special kind of iterator a generator is a function that returns an iterator and an iterator is an object