from collections.abc import Iterable
list1 = [1, 2, 3]
print(isinstance(list1, Iterable))
isinstance Determine whether it is an iteratable object
Can be next() The object that function calls and returns the next value continuously is called an iterator
s = "123456"
s = iter(s)
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
An error will be reported when the range is exceeded StopIteration
Determine whether it is an iterator
from collections.abc import Iterable, Iterator
s = "123456"
s = iter(s)
print(isinstance(s, Iterable))
When the range is exceeded, the following methods can be used to prevent error reporting
s = "123456"
s = iter(s)
while 1:
try:
print(next(s))
except StopIteration:
print(" End of the iteration !")
break
Generator Expressions
List derivation List generator
l = [i for i in range(100)]
for i in range(100):
l.append(i)
print(l)
l = (i for i in range(1000000000000))
print(l)
print(next(l))
print(next(l))
print(next(l))
print(next(l))
for i in range(101):
print(next(l))
Generator function keyword yield
When there is yield When a keyword This function returns a generator , Can only be used for iterative operations . use next() In the process of calling the generator , Every encounter yield Keyword will pause the function and keep the running information of the current function , return yield Value , And continue to execute downward from the current position at the next execution
def my_generator():
for i in range(1, 6):
print(f" The first {
i} Execution times yield Before ")
yield i
print(f" The first {
i} Execution times yield after ")
g = my_generator()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
Simple calculation method
def ficonacci():
a, b = 0, 1
while 1:
yield a
a, b = b, a+b
f = ficonacci()
for i in range(1000):
print(next(f))