#!/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")