找回密码
 会员注册
查看: 20|回复: 0

python打怪练习

[复制链接]

2万

主题

0

回帖

7万

积分

超级版主

积分
72033
发表于 2024-9-8 00:23:18 | 显示全部楼层 |阅读模式
1.求一个数的幂值defmi(a,b):c=aforiinrange(b-1):a=a*creturnaprint(mi(2,4))123456782.输出斐波那契数列deffeibonaqi(n):l=[]a=1b=1foriinrange(n):l.append(a)l.append(b)a=b+ab=a+bprint(l)feibonaqi(5)123456789101112133.输出特定字典数据keys=['name','old','score']values=[['yee',3,99],['rose',18,8],['green',30,90]]要输出结果:[{'name':'yee','old':3,'score':99},{'name':'rose','old':18,'score':8},{'name':'green','old':30,'score':90}]123456正确示范:keys=['name','old','score']values=[['yee',3,99],['rose',18,8],['green',30,90]]l=[]forvalueinvalues:d={}foriinrange(len(keys)):d[keys[i]]=value[i]l.append(d)print(l)1234567891011错误示范:keys=['name','old','score']values=[['yee',3,99],['rose',18,8],['green',30,90]]l=[]d={}forvalueinvalues:foriinrange(len(keys)):d[keys[i]]=value[i]l.append(d)print(l)1234567891011错误原因:列表追加的元素指向的是同一个字典d,若d字典的键值变化也会同步到列表例如:cc=[]aa={'name':'green','old':30,'score':90}cc.append(aa)aa['name']='yee'aa['old']=3aa['score']=99cc.append(aa)print(cc)12345678输出结果是:[{‘name’:‘yee’,‘old’:3,‘score’:99},{‘name’:‘yee’,‘old’:3,‘score’:99}]4.分批次读取文件内容,每次读取100行defread_file():withopen('id.txt','r')asfile:print(type(file))fori,jinenumerate(file,1):print(i,j)ifi%100==0:yieldcontent=read_file()whileTrue:print('--------------------------------------------')try:content.__next__()exceptStopIteration:break1234567891011121314151617改良版:defread_file():withopen('id.txt','r')asfile:mark=[]fori,jinenumerate(file,1):mark.append(j.strip('\n'))ifi%100==0:yieldmarkmark=[]ifmark==[]:yieldmarkcontent=read_file()foriincontent:print(i)print('----------')12345678910111213141516
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2025-1-10 23:07 , Processed in 0.453205 second(s), 25 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表