python学习笔记------迭代器和生成器(二)

# 对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个异常以终止迭代(只能后退不能前进)
# x = 'hello'
# # 遵循迭代器协议,把字符串转化为可迭代对象
# iter_test = x.__iter__()
#
# print(iter_test.__next__())
# print(iter_test.__next__())
# print(iter_test.__next__())
# print(iter_test.__next__())
# print(iter_test.__next__())


# 生成器即一种数据类型,这种数据类型内部自动实现了迭代器协议(其他数据类型需要调用自己内部的iter方法),所以生成器也是可迭代对象
# def test():
#     yield 1
#
# print('生成器表达式',test())

# 三元表达式
# name = 'ads'
# name = 'sasja'
# test = 'SB' if name == 'ads' else '帅哥'
#
# print(test)
# 列表解析
#
# aglist = []
#
# for i in range(10):
#     # 字符串拼接
#     aglist.append('鸡蛋%s' %i)
#
# print(aglist)
#
# l = ['鸡蛋%s' %i for i in range(10)]
# print(l)
# # 三元表达式 '鸡蛋%s'  for i in range(10)  if i > 5 ,主体为for 循坏
# ll = ['鸡蛋%s' %i for i in range(10) if i > 5]
# # ll = ['鸡蛋%s' %i for i in range(10) if i > 5 else i]#没有四元
#
# print(ll)

# l3 = ('鸡蛋%s' %i for i in range(10))
# # 方法名即地址
# print('生成器函数形式',l3)
# print(l3.__next__())
# print(l3.__next__())

# def  testSheng():
#
#      print('我的第1次打印=========')
#      yield '1'
#
#      print('我的第2次打印=========')
#      yield '2'
#
#      print('我的第3次打印=========')
#      yield '3'
#
#      print('我的第4次打印=========')
#      yield '4'
#
#
# test = testSheng()
# print(test.__next__())
# print(test.__next__())
# print(test.__next__())
# print(test.__next__())
# 生成器的好处   1:执行效率高  延迟计算,一次返回一个结果,也就是说不会一次生成所有的结果
# 2:有效提高代码的可读性


# import time
# def product_baozi():
#     for i in  range(100):
#         time.sleep(3)
#         yield ('一屉包子%s' %i)
#
#
# baozi = product_baozi()
# # 不允许用下面的方式调用方法  product_baozi()调用结束后,下次再调用相当于重新执行
# # print(product_baozi().__next__())
# print(baozi.__next__())
# print(baozi.__next__())
# print(baozi.__next__())
# print(baozi.__next__())
# print(baozi.__next__())
# print(baozi.__next__())

def getPopulation():
    with open('people') as file:#读取文件内的信息
        for i in file:
            yield  i


people = getPopulation()
# print(people)
# dic = eval(people.__next__())# 因为是从文件里面读取出来的,所以默认为字符串类型。需要使用eval函数来获取字符串的类型
# print(dic['population'])

# for i in people:
#     peoDict = eval(i)
#     print(peoDict['population'])

# 'population' 文件中存的是字符串
# 获取总的人数
# data = sum(eval(eval(i)['population']) for i in people)
# print(data)

data2 = eval(people.__next__())
print(data2['population'])

# 触发生成器函数的几种方法 .__next__() next() .send(None)

猜你喜欢

转载自blog.csdn.net/weixin_39180334/article/details/81457844