当前位置:网站首页>Iterators and generators

Iterators and generators

2022-07-06 15:09:00 Naive code writing

Iteratable object

list 、 Tuples 、 aggregate 、 Dictionaries 、 Objects such as strings are called iteratable objects

iterator :

x=[1,2,3]
i=iter(x)
print(next(i))
print(next(i))
print(next(i))#next  Only one number is iterated out each time , Iterate from front to back , There are several numbers that can be iterated several times , More than will prompt that there is no iteratible object 

generator :
Use yield :

Complex generator :

def gen(n):
    for i in range(n):
        yield i*i
x=gen(5)
for i in x:
    print(i)

Output results :
0
1
4
9
16

Simplification generator :

a=(i*i for i in range(5))
for i in a:
    print(i)

The output is the same

What does the generator do : Save storage space and time , The first step is to directly generate the function , There is no need to calculate ,

import sys
import time
t1=time.time()
mylist = [i for i in range(10000000)]
t2=time.time()
print(" Elapsed time :",t2-t1)
print(" Occupancy space :",sys.getsizeof(mylist))
t3=time.time()
mygen = (i for i in range(10000000))
t4=time.time()
print(" Elapsed time :",t4-t3)
print(" Occupancy space :",sys.getsizeof(mygen))

Output results :
Elapsed time : 0.5699965953826904
Occupancy space : 89095160
Elapsed time : 0.0
Occupancy space : 104

practice :
Construct a generator to calculate the absolute value .

b=[1,2,3,-4,-5,-3]
a=(abs(x) for x in b  )# At this time a It's a list of all positive numbers 
for i in a:
    print(i)

Output results :
1
2
3
4
5
3

原网站

版权声明
本文为[Naive code writing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131324009569.html