首页 技术 正文
技术 2022年11月22日
0 收藏 599 点赞 2,252 浏览 761 个字

练习

杨辉三角定义如下:

       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对象。

(来自廖雪峰官网)


就酱

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,084
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,559
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,408
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,181
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,818
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,901