Python iterator (Iterator)

Copyright, without permission, is prohibited reprint


chapter


Python iterator (Iterator)

Iterator is an object that contains a limited number of values.

An iterator object may be iterated, you can traverse all values ​​in the iterator.

Technically, in Python, iterator iterator protocol is to achieve the object, the agreement by the process __iter__()and __next__()composition.

Iterable data types

Lists, tuples, and dictionaries are available iterative set of objects, which can be obtained from the iterator.

All of these objects are available iter()method to get an iterator:

Examples

Obtaining an iterator from the tuple, and print each traversal value:

mytuple = ("自行车", "汽车", "高铁")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Strings are iterables from which you can get an iterator:

Examples

Use iterates over the string:

mystr = "自行车"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))

for loop iterates

We can also use a for loop to iterate an iterator:

Examples

Iteration tuple values:

mytuple = ("自行车", "汽车", "高铁")

for x in mytuple:
  print(x)

Examples

Iterative character of the string:

mystr = "自行车"

for x in mystr:
  print(x)

forInternal circulation was actually obtain iterator, and next()method call.

Creating an iterator

To create an object iterator can become iteration, you must implement the methods: __iter__()and __next__().

__iter__()Method must always return an iterator object itself.

__next__()The method must return the next item in the sequence.

Examples

Creating a Returns iterator, starting from 1, incremented by 1 each sequence item (return 1,2,3,4,5, etc.):

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self
    
  def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

StopIteration

The example above next()calls will always continue, we can use the StopIterationstatement to stop iteration.

In the __next__()process, we can add the termination condition based on the number of iterations to raise an error:

Examples

After 20 iterations stop:

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self
    
  def __next__(self):
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
  print(x)

Guess you like

Origin www.cnblogs.com/jinbuqi/p/11387518.html