An article takes you through python iterators and generators
- 2021-11-24 02:23:35
- OfStack
Directory python Iterators and Generators
1. Iterator
2. Generator Summary
python Iterators and Generators
1. Iterator
2. Generator Summary
python Iterators and Generators
1. Iterator
Here, use a dictionary example
while True belongs to an infinite loop. Because the dictionary elements are limited, try is used for exception handling
dict1 = {
'name':'laowang',
'age':18,
'high':180
}
iterator = dict1.__iter__()
while True:
try:
res = iterator.__next__()
except:
break
else:
print(res,dict1[res]
Results:
name laowang
age 18
high 180
2. Generator
First, look at the derivation of the following list
list1 = [i for i in range(1,10)]
# Results
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Generator
list1 = (i for i in range(1,10))
# Results
<generator object <genexpr> at 0x7fa491ea3410>
# generator Generator
# Generator function
def func1():
for i in range(1,10):
yield i
res = func1() # Generator object
for i in res:
print(i)
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!