Iterators and the role of iterators

# iterator
'''
Iteration is a way of accessing the elements of a collection, an iterator is an object that remembers where to traverse
The iterator object is accessed from the first element of the collection until all elements have been accessed.
If you want to access an element, you need to traverse all the elements in front of this element before you can access it
'''
#1. Iterable objects, like (1), (2) these objects are called iterable objects (Iterable)
#(1) The data types of the direct-action for loop are: list/tuple/dict/set/str
#(2) generator: generator and generator function
# list1 = [11,22,33]
# for i in list1:
#     print(i)
# for char in 'i love china!':
#     print(char)

#2. Determine whether to iterate
from collections import Iterable,Iterator
# def outPrint(msg):
# # Determine if msg is iterable
#     flag = isinstance(msg,Iterable)
#     if flag:
#         for i in msg:
#             print(i)
#     else:
#         print(msg)
# outPrint(1)
# outPrint([11,22,33])

#exercise 1
# print(isinstance([],Iterable))#True
# print(isinstance((),Iterable))#True
# print(isinstance({},Iterable))#True
# print(isinstance('love',Iterable))#True
# print(isinstance((x for x in range(10)),Iterable))#True

# The generator can not only act on the for loop, but also can be called continuously by the next function, and the next value after the meal, until
# Finally, a StopIterable exception is thrown, indicating that the next value cannot be returned

#exercise 2
# An object that can be called by the next() function and continuously returns the next value is called an iterator (Iterator)
#If it is an iterator object, it must be iterable
# Determine the iterator object
# print(isinstance([],Iterator))#False
# print(isinstance((),Iterator))#False
# print(isinstance({},Iterator))#False
# print(isinstance('love',Iterator))#False
# print(isinstance((x for x in range(10)),Iterator))#True

#Generators are Iterator objects, but although list/dict/str are Iterable, they are not Iterators

#iter() function
#Turn list/dict/str and other Iterable containers into Iterators
list2 = [11,22,33]
# print(next(list2))
list2 = iter(list2)
print(next(list2))
print(next(list2))
print(next(list2))
# print(next(list2))
'''
Summarize:
1. Any object that can be used in a for loop is Iterable
2. Any object that can act on a function of next() is an Iterator
3.iter() function is used to turn Iterable container into Iterator

Iterator extension:
For "streaming" data processing to reduce memory consumption:
For example, when processing files, large videos, etc., suddenly taking all the data out and putting it in the memory will cause the program to consume a lot of memory
Generally, we process the files part by part
'''
for text_line in open('userInfo.txt'):
    print(text_line)
    break

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324655926&siteId=291194637