生成器,迭代器
2018-04-03 本文已影响0人
流蓝浅
1、有规律的列表,[] ==> () 生成器
a = [x for x in range(9)]
2、规律很难有一个简单表达式表示出来
斐波拉契数列(Fibonacci)
前两个数之和等于3个数
def fib(max):
first,second,index = 1,1,0
while index < max:
first,second = second,first+second
print(first)
index += 1
xss
sql web
"""
斐波拉契生成1.0版
"""
# def fib(max):
# first,second,index = 1,1,0
# while index < max:
# first,second = second,first+second
# print(first)
# index += 1
# fib(10)
"""
斐波拉契生成1.0版
如果生成的数列数据特别庞大的时候,内存的占有就很大
"""
# ls = []
# def fib(max):
# first,second,index = 1,1,0
# while index < max:
# first,second = second,first+second
# ls.append(first)
# index += 1
# fib(10)
# print(ls)
def fib(max):
if max == 1:
return 1
if max == 2:
return 2
return fib(max-1) + fib(max - 2)
# yield关键字,会将函数转换为一个生成器
# def fib(max):
# first,second,index = 1,1,0
# while index < max:
# first,second = second,first+second
# yield first # 暂停一下,返回一个返回值 只能用next接受
# index += 1
#
# res = fib(10)
# print(res)
#
# def fib(max):
# first,second,index = 1,1,0
# while index < max:
# first,second = second,first+second
# print("yield之前")
# yield first
# print("yield之后")
# index += 1
# yield关键字生成生成器时,调用函数,该函数不会执行,只会转化为生成器,返回给返回值
# res = fib(10)
# print(res)
# print(next(res))
# print(next(res))
# for x in res:
# print(x)
""""
send主要用于控制生成器的流程
"""
def demo1():
while True:
temp = yield 1
if temp == 1:
print("打印数据")
elif temp == 2:
print("存储数据")
elif temp == 3:
print("展示数据")
res = demo1()
# 我们使用send来控制生成器函数的流程的时候
# 应该首先让生成器next
next(res)
res.send(2)
res.send(1)
iter()可以将可迭代的对象转换为迭代器
# ls = [1,3,4,45,6,67,77,]
# for x in ls:
# print(x)
# t = (1,3,4,45,6,67,77,)
# for x in t:
# print(x)
# str = "liujianhongisgoodman"
# for x in str:
# print(x)
# dict = {"name":"liujianhong","age":16,"sex": "nan"}
# for k,v in dict.items():
# print(k,v)
# ls = (x for x in range(100))
# for x in ls:
# print(x)
from collections import Iterable,Iterator
#Iterable 类型用来判断是否可被迭代的对象
ls = (x for x in range(100))
a = 10
# 判断某个对象是否可以被迭代
# isTrue = isinstance(a,Iterable)
# print(isTrue)
dict = {"name":"liujianhong","age":16,"sex": "nan"}
t = (1,3,4,45,6,67,77,)
# iter 是一个全局函数
# 可以将可迭代的对象转换为迭代器
ts = iter(t)
print(isinstance(ts,Iterator))
print(ts.__next__())