python simple generator and iterator

Keywords: Python

iterator

  • Iteration is one of Python's most powerful functions and a way to access collection elements.
  • Iterator is an object that can remember the location of traversal.
  • Iterator objects are accessed from the first element of the collection until all elements are accessed. Iterators can only move forward and not backward.

Iterable object

Objects that can return an iterator can be called iterative objects. Iterative objects implement the _iter_method, which returns an iterator object.
Iterable data types in Python: list, tuple, dictionary dict, set, string
Non-Iterative Data Types: Numbers
Iterability of objects can be achieved by rewriting _iter_ method

# Using module Iterable to detect whether an object can iterate
from collections.abc import Iterable

a = ['hello', 'hi', 'good', 'yes', 'no']

for x in a:
    print(x)

for x in range(10):
    print(x)
# Objects that can be traversed through a for loop are all Iteratives

# for x in 23:
#   print(x)

# Judging whether a can be iterated
print(isinstance(a, Iterable))
c = 12
print(isinstance(c, Iterable))

# Rewriting _iter_ method can realize the iteration of object
class Demo(object):
    def __iter__(self):
        pass


d = Demo()
print(isinstance(d, Iterable))

# Iterative objects do not necessarily allow traversal of for loops
for m in d:
    print(m)

Customize an Iterable Object
The value of the iterated object can be obtained by next().

class MyIterator(object):
    def __init__(self,n):
        self.n = n
        self.current = 0

    def __next__(self):
        if self.current < self.n:
            self.current += 1
            return 100
        raise StopIteration


my_iter = MyIterator(5)
print(isinstance(my_iter, Iterator))


class Demo(object):
    def __init__(self,n):
        self.n = n

    def __iter__(self):
        return MyIterator(self.n)


d = Demo(10000)
# for m in d:
#    print(m)
print(d.__iter__().__next__())
print(d.__iter__().__next__())
print(d.__iter__().__next__())
print(d.__iter__().__next__())

Simple Iterator

Rewrite the _iter_ method. An object is an iteratable object. If a class wants to be an iterator, it needs to rewrite the _next_ method.
Stopiteration: Used to denote the end of an iteration, throw Stopitation to tell the interpreter that the iteration is complete to prevent the occurrence of a dead cycle

class MyIterable(object):
	def __init__(self,n):
		self.n = n
		self.current = 0
	def __iter__(self):
		return self
	def __next__(self):
		if self.current < self.n:
			self.current += 1
			return self.current
		raise StopIteration

my_interable = MyIterable(10)
for i in my_interable:
	print(i)
	


Using Iterator to Realize Fibonacci Sequence

class Feibonacci(object):
	"""docstring for Feibonacci"""
	def __init__(self, n):
		self.n = n
		self.current = 0
		self.num1 = 1
		self.num2 = 1

	def __iter__(self):
		return self

	def __next__(self):
		if self.current < self.n:
			x = self.num1
			self.current += 1
			self.num1, self.num2 = self.num2, self.num1 + self.num2
			return x
		raise StopIteration


fb = Feibonacci(10)

list1 = []

for i in fb:
	list1.append(i)

print(list1)

generator

  • A generator can be said to be a function, which differs from a normal function in that it uses yield to return, not return.
  • In the process of calling generator, every time yielding is encountered, the function pauses and saves all current running information, returns the value of yielding, and continues to run from the current position the next time the next() method is executed.
  • Calling a generator function returns an iterator object.
  • Generator is a special iterator

Simple Generator Implementation

Note: The loop in the generator must use the while loop. The for loop can't implement the generator.

def mygeneration(n):
	current = 0
	while current < n:
		yield current
		current += 1

mg = mygeneration(10)
for i in mg:
	print(i)


Generator Implementing Fibonacci Sequence

def Febonacci(n):
	current = 0
	num1 = 1
	num2 = 1
	while current < n:
		current += 1
		yield num1
		num1, num2 = num2, num1 + num2
fb = Febonacci(10)

list1 = []

for i in fb:
	list1.append(i)

print(list1)

Posted by samuelxin on Sat, 10 Aug 2019 05:39:41 -0700