Details and examples of the python iterator and iter of functions

  • 2020-05-27 06:01:32
  • OfStack

The iterator and the iter() function in python

The iterator provides an interface for a class sequence object. python's iteration seamlessly supports sequence objects, and it also allows programmers to iterate over non-sequence types, including user-defined objects. Iterators are neat to use. You can iterate over objects that are not sequences but represent the behavior of a sequence, such as the keys of a dictionary, the lines of a file, and so on. The role of the iterator is as follows:

The & # 8226; An iterator interface for scaling is provided.
The & # 8226; The list iteration provides performance enhancements;
The & # 8226; Improved performance in dictionary iteration;
The & # 8226; Create a real iterative interface instead of the original random object access;
The & # 8226; Backward compatibility with all existing user-defined classes and extended mock sequences and mapped objects;
The & # 8226; When iterating over nonsequential collections, such as maps and files, you can create more concise and readable code


#iter and generator
#the first try
#=================================
i = iter('abcd')
print i.next()
print i.next()
print i.next()

s = {'one':1,'two':2,'three':3}
print s
m = iter(s)
print m.next()
print m.next()
print m.next()

D:\Scirpt\Python\Python advanced programming > python ch2_2.py


a
b
c
{'three': 3, 'two': 2, 'one': 1}
three
two
one

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: