Iterator generator

Posted by saidbakr on Thu, 12 Dec 2019 19:04:38 +0100

I. iterator

  • Iteratable: an object that can iterate, and contains the function "iterator" ()
  • Iterator: iter ator, which contains the \\

Characteristic:

  • Save memory
  • Inertia mechanism
  • Can't repeat, can only execute downward

1. Iteratable objects

1) judge whether an object is an iterative object

  • Use the dir function to see if there is a "iter" method in the method defined in the class

If the "iter" can be found, the object of this class is an iterative object.

print(dir(str))
print(dir(list)) //Result: [
'__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
  • Through the isinstance() function

If the return value is True, the object is iterative, otherwise it is not.

from collections import Iterable

lst = [11, 22, 33]

print(isinstance(lst, Iterable))  # True

2. iterator

  • The iterator itself is iterative, so there is an iterator method in the class.

1) judge whether an object is an iterator

  • Use the dir function to see if there is a "next" method in the method defined in the class
lst = [11, 22, 33]
ret = lst.__iter__()

print("__next__" in dir(ret))  # True

 

  • Through the isinstance() function
from collections import Iterator

lst = [11, 22, 33]
ret = lst.__iter__()

print(isinstance(ret, Iterator))  # True

 

2) iterator value

Get iterator data through next

lst = [11, 22, 33]
ret = lst.__iter__()

print(ret.__next__())
print(ret.__next__())
print(ret.__next__())


//Result:
11
22
33

If the number of acquired elements exceeds the length of iterator elements, StopIteration will be reported as an error

lst = [11, 22, 33]
ret = lst.__iter__()

print(ret.__next__())
print(ret.__next__())
print(ret.__next__())
print(ret.__next__())  # StopIteration

3) for loop internal code

ret = lst.__iter__()

while 1:
    try:
        el = ret.__next__()
        print(el)
    except StopIteration:
        break

 

3. Iteratable object ----- > iterator

  • An iteratable object is not necessarily an iterator, but can be converted to an iterator by the iterator method
lst = [11, 22, 33]
ret = lst.__iter__()

print("__next__" in dir(ret))  # True

Topics: Python