def myegg(retlist): for i in retlist: rec = yield i mydict = [ {"name":"厉智","age":31}, {"name":"陈培昌","age":21}, {"name": "程劲", "age": 20}, ] b = myegg(mydict) obj = b.__next__() print("喜欢{},芳龄{}".format(obj['name'],obj['age'])) obj2 = b.__next__() print("喜欢{},芳龄{}".format(obj2['name'],obj2['age'])) obj3 = b.__next__() print("喜欢{},芳龄{}".format(obj3['name'],obj3['age']))
打印结果:
喜欢厉智,芳龄31
喜欢陈培昌,芳龄21
喜欢程劲,芳龄20
或者循环遍历访问,因为生成器也是可迭代的 b = myegg(mydict) for i in b: print("喜欢{},芳龄{}".format(i['name'], i['age']))