How to understand Python Iterators and generators ? stay Python in , Use for ... in ... It can be done to list、tuple、set and dict Data types are iterated , You can filter out all the data . as follows :
for element in [1, 2, 3]:
print(element)
for element in (1, 2, 3):
print(element)
for key in {'one':1, 'two':2}:
print(key)
for char in "123":
print(char)
for line in open("myfile.txt"):
print(line, end='')
1、 iterator
The string , list , Use built-in functions iter Convert to an iteratable object , Use next keyword , Iteratable objects take one value at a time . Like the following code :
nums = [1,2,3,4]
nums = iter(nums)
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))
Output
1
2
3
4
If it exceeds the length of the data , Will be an error StopIteration
nums = [1,2,3,4]
nums = iter(nums)
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums))
print(next(nums)) # Over data length , Report errors StopIteration
2、 generator
Using generators, you can create iterators . The generator mainly uses yeild keyword , Every time you call next When it comes to yeild The definition of the corresponding . for example : We need to take 10~20 Data between , In steps of 2, You can use the following code
for x in range(10,20,2):
print(x)
But if the step size is set to 0.5, The following code :
for x in range(10,20,0.5):
print(x)
Will be an error
TypeError: 'float' object cannot be interpreted as an integer
This is the time , We can use The generator comes from defining a function
def drange(start,stop,step):
x = start
while x< stop:
yield x
x += step
for x in drange(10,20,0.5):
print(x)
Another example :
Given a string , Flashback to arrange :
def reverse(data):
for x in range(len(data)-1,-1,-1):
yield data[x]
for x in reverse('gold'):
print(x)
See here , I believe that we can understand Python Iterators and generators have a certain understanding . More about dry goods , In the erudite Valley IT Training platform , From zero basis to advanced promotion, the learning content of each stage of learning is waiting for you !
Zhengzhou painless people hospital which good http://fk.zztjyy.com/
Zhengzhou see gynecology which hospital is good http://www.zztjfk.com/
Zhengzhou see gynecology which good http://www.xasgfuke.cn/