【Python习题总结】统计累加方法

1.例如要统计不同类型文件的大小总和
(1)列表方法(较难):
resList=[] #[[类型1,大小1],[类型2,大小2]]

inFlag=False  #变量法/标志位法
for one in resList:
  if one[0]==fileType:
    one[1]+=fileSize
    inFlag=True
 #所有的for执行完之后,才知道这个fileType是否已存在
if inFlag==False:
  resList.append([fileType,fileSize])

(2)字典方法(较简单):
resDict={‘类型1’:大小1,‘类型2’,大小2}

if fileType not in resDict
  resDict[fileType]=fileSize
else:
resDict[fileType]+=fileSize

2.还遇到过型如{学生id:[{‘课程id’:课程id,‘签到时间’:签到时间}]}这样题中给出了看起来复杂的要求格式,不要慌乱,一层一层去剖析它
在这里插入图片描述

for line in lines:
  toAdd={
    
    'lessonid':lessonid,'time':time}
  if userid not in retDict:
    retDict[userid]=[]
  retDict[userid].append(toAdd)

猜你喜欢

转载自blog.csdn.net/jylsrnzb/article/details/106502200
今日推荐