zoukankan      html  css  js  c++  java
  • 022_generator

    #!/usr/bin/env python
    # Author:liujun

    # List Comprehensions
    # A list comprehension generates all elements at once ,which consumes a lot of memory
    # version 1
    ls = [ i*2 for i in range(10) ]
    print(ls)

    # version 2
    def func(i):
    return i*2 + 1
    ls = [ func(i) for i in range(10)]
    print(ls)



    # list generator
    # A list generator doesn't generate any elements, elements are generated only when they are accessed
    lsg = (( func(i) for i in range(20)))
    print(lsg) # You can not print lsg directly
    # If you want to print lsg,do the following
    for i in lsg:
    print(i)

    lsg2 = (( func(i) for i in range(20)))
    print(lsg2.__next__())
    print(lsg2.__next__())
    print(lsg2.__next__())
    print(lsg2.__next__())
    print(lsg2.__next__())
    print(lsg2)




    def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
    yield b # b is the value you want to return.
    a,b = b,a+b
    n = n+1
    f = fib(100) #f is a generator
    while True:
    try:
    x = next(f)
    print("f:",x)
    except StopIteration as e:
    print("Generator return value:",e.value)
    break




    def consumer(name):
    print("%s is ready to eat buns"%(name))
    while True:
    baozi = yield
    print("bun [%s] is coming here and eaten by [%s]"%(baozi,name))

    def producer(name):
    c = consumer("A")
    c2 = consumer("B")
    c.__next__()
    c2.__next__()

    print("I am starting to make buns")
    for i in range(10):
    c.send(name)
    c2.send(name)
    producer("meat")
  • 相关阅读:
    Linux 下卸载MySQL 5
    Solr使用入门指南
    GridView行编辑、更新、取消、删除事件使用方法
    从最大似然到EM算法浅解
    MySQL中数据表的增操作
    趣味Java算法题(附答案)
    nodeValue的兼容问题
    边记边学PHP-(十五)MySQL数据库基础操作2
    素数推断算法(高效率)
    expect
  • 原文地址:https://www.cnblogs.com/liujun5319/p/9615663.html
Copyright © 2011-2022 走看看