**将列表中的所有字符串转换为小写:
li = ["Hello", "WESTOS", 1, 43]
[i. lower() for i in li if isinstance(i,str)]
案例1:[i for i in range(10000000)]
如上,用列表生成式打印一串数字,当生成时元素即打印,会占用内存,range后面的数越大,越占内存。为了解决这一问题,可以引用生成器:
(i for i in range(10000000)) ##注意此处用的是小括号
读取生成器元素的方式:
法一:g.next() ##一次返回一个值,当next次数大于生成个数时会报错
法二:from collections import Iterable
g = (i**2 for i in range(4))
print isinstance(g.Iterable)
for i in g:
print i ##此处利用生成器的可迭代性
案例2:Fibonacci数列:[1, 1, 2, 3, 5, 8, 13, 21,...]
*生成fib数列的函数,n代表生成数个数
def fib(n):
n, a, b = 0, 0, 1
while n < max:
print b
a, b = b, a + b
n += 1
fib(10)
使用yield关键字(输出生成器)生成Fibonacci数列:
def fib(n):
n, a, b = 0, 0, 1
while n < max:
yeild b
a, b = b, a + b
n += 1
g = fib(10)
for i in g:
print i
**python中两值交换:x, y = y, x
案例3:生成器生成生产者消费者模型
coding:utf-8
latiao_agency = []
kind = ["丢丢辣", "微辣", "麻辣", "特辣", "超级辣"]
def consumer(name):
print "%s 准备买辣条" %(name)
while True:
kind = yield
latiao_agency.remove(kind)
print "客户[%s]买了[%s]口味的辣条。。。。。。" %(name,kind)
#g = consumer("肃敏")
#g.next()
##send方法将值传给yield所在位置的变量;
#g.send("特辣")
import time
def producer(name, *kind):
#c1和c2是生成器对象
#c1 = consumer("肃敏")
#c2 = consumer("小闫")
#c1.next()
#c2.next()
print "准备制作辣条。。。。。。"
for i in kind:
time.sleep(3)
print "[%s]制作了[%s]口味的辣条,准备提供给消费者。。。。。。" %(name, i)
latiao_agency.append(i)
#c1.send(i)
#c2.send(i)
producer("长虹", "微辣", "麻辣", "超级辣")
c1 = consumer("肃敏")
c1.next()
c1.send("微辣")
print "目前本店辣条口味:"
for i in latiao_agency:
print i
案例4:迷你聊天机器人
#coding:utf-8
#函数中有yield,代表调用函数时,返回值为生成器;
def chat_robot():
res = ''
while True:
#遇到yield时停止运行
received = yield res
if '你好' in received or 'hi' in received:
res = "你好,欢迎来到火星!我是小伊!"
elif '多少岁' in received or 'age' in received:
res = "我永远8岁!"
elif '再见' in received or 'bye' in received:
res = "再见!"
else:
res = "我不知道你在说什么,请说人话!"
#Chat是生成器
Chat = chat_robot()
#Chat.next()和next(Chat)效果相同;
next(Chat)
while True:
r_input = raw_input("我>>")
if not r_input:
continue
elif r_input.lower() == 'q':
print "已退出!"
break
else:
response = Chat.send(r_input)
print response
本文介绍Python中生成器的基本概念及多种应用场景,包括列表转换、高效数字生成、Fibonacci数列生成、生产者消费者模型及聊天机器人的实现。

被折叠的 条评论
为什么被折叠?



