2019-02-02 Python学习——生成器杨辉三角,迭代器与可迭代对象的区别

时间:2023-03-09 02:21:24
2019-02-02 Python学习——生成器杨辉三角,迭代器与可迭代对象的区别

练习

杨辉三角定义如下:

     	  1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1

把每一行看做一个list,试写一个generator,不断输出下一行的list:

def triangles():
list = [1]
while list:
yield list
newlist = list.copy()#进行一次深复制
for i in range(len(list)+1):
if(i==0):
pass
elif(i==len(list)):
newlist.append(1)
elif(i!=0 and i!=len(list)):
newlist[i] = list[i] + list[i-1]
list = newlist.copy()

廖雪峰网站上的题目,贴一下自己的

网上更简单的

def triangles():
list = [1]
while True:
yield list
list = [list[i]+list[i+1] for i in range(len(list)-1)]
list.insert(0,1)
list.append(1)

insert没有想到哎

迭代器和可迭代对象

from collections import Iterable
from collections import Iterator
isinstance( , Iterable) #用于判断是否为可迭代对象
isinstance( , Iterator) #用于判断是否为迭代器

总结

凡是可作用于for循环的对象都是Iterable类型;

凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;

集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。

(来自廖雪峰官网)


就酱