We can use lists to store data, but when the data is large, creating a list of stored data will take up memory. The generator is a method that does not take up much computer resources.
def myegg(retlist):
for i in retlist:
rec = yield i
mydict = [
{"name":"Li Zhi","age":31},
{"name":"Chen Peichang","age":21},
{"name": "Cheng Jin", "age": 20},
]
b = myegg(mydict)
obj = b.__next__()
print("Like {}, Fang Ling{}".format(obj['name'],obj['age']))
obj2 = b.__next__()
print("Like {}, Fang Ling{}".format(obj2['name'],obj2['age']))
obj3 = b.__next__()
print("Like {}, Fang Ling{}".format(obj3['name'],obj3['age']))
Print the result:
Like Li Zhi, Fang Ling 31
Like Chen Peichang, Fang Ling 21
Like Cheng Jin, Fang Ling 20
Or iterate through the visit, because the generator is also iterable
b = myegg(mydict)
for i in b:
print("Like {}, Fang Ling{}".format(i['name'], i['age']))