生成器特性及send用法

#生成器特性
# def get_polulation():
#     ret=[]
#     with open('人口普查','r',encoding='utf-8')as f:
#         for i in f:
#             ret.append(i)
#     return ret
# print(get_polulation())


'''
def get_polulation():
    with open('人口普查','r',encoding='utf-8')as f:
        for i in f:
            yield i
g=get_polulation()
#TypeError: string indices must be integers(类型错误:字符串索引必须是整数)
#取出来是字符串
#print(g.__next__()['population'])
#将字符串转换为字典
sl=eval(g.__next__())
#返回对象
print(type(sl))
print(sl['population'])

#取和
# res= 0
# for p in g:
#     p_dic=eval(p)
#     print(p_dic['population'])
#     res+=p_dic['population']
# print(res)

#生成器,取和
all_pop = sum (eval(i)['population']for i in g )
print(all_pop)

'''
#send的用法
def test():
    print('开始了')
    yield 1
    print('第一次')
    yield 2
    print('第二次')
t=test()

res=t.__next__()#next(t)方法二
print(res)
#不赋值就不返回值
#t.__next__()
#send把值传给yield
t.send(None)

 

posted @ 2018-10-29 16:58  汉魂县令  阅读(47)  评论(0)    收藏  举报