top of page

Python Learning

Photo du rédacteur: zoe zhaozoe zhao

Dernière mise à jour : 26 juil. 2023


在学习Data Science for Design这门课的时候跟随老师给到的Jupyter Notebook中的内容学习了Python,还好之前上了密歇根大学的Coursera Python for everybody的课程,有了基础之后再学习新内容会容易理解很多。


在第三个文件Loops and conditions中遇到了一个有趣的练习,加深了对循环的理解。


处理csv文件时用到了 glob 来找寻符合命名规则的文件 import glob glob.glob('*.csv) 此处*代表任意数位字符,?代表至少一个字符 用python打开csv时也用到了filehandle 使用到的语句: with open(--文件名,‘r’)as csvfile: 此处卡了很久的一道题,先是找到了所有csv文件,对csv中line进行遍历 总结每一行值的合 总结每个文件中所有行的合的总合 总结所有文件的总合 应该分为三层

目标输出结果为: OPENING FILE: A.CSV ROW TOTAL: 15 IS 15 TOTAL IN FILE A.CSV OPENING FILE: B.CSV ROW TOTAL: 14 TOTAL IN FILE B.CSV IS 14 OPENING FILE: D.CSV ROW TOTAL: 14 ROW TOTAL: 12 TOTAL IN FILE D.CSV IS 26 OVERALL TOTAL IS 55 复盘: overalltotal=0

#在所有循环开始前,设定overall总和初始值为零 for i in glob.glob('*.csv'): with open( i,'r') as csvfile: print('Opening file: '+i)

#此处i是str格式 所以可以+ filetotal=0 # 设定文件初始总和为0 for line in csvfile:

#疑问 为什么不能for line in i: rowtotal=int(line[0])+int(line[2])+int(line[4]) # 因为还没有学pandas只能先用笨方法把三个cell里的值相加 print('Row total:'+str(rowtotal)) filetotal=filetotal+rowtotal #这一步很重要,d.csv有两个line所以会在此for循环中循环两次,要把filetotal放进这个循环里参与迭代才能够得到filetotal,之前就是放错了位置卡了很久。 print('Total in file '+ i +' is '+ str(filetotal)) overalltotal=overalltotal+filetotal #注意这里已经跳出line的循环了,是在file的for循环框架里。overall在这里进行相加才能得到所有file便利后的总和值。 print('Overall total is ' +str(overalltotal)) #跳出所有循环print总和 这道题目很好的让人理解了循环嵌套,层与层之间的关系,初始值应该在何处设定,以及应该在何处进行运算。 另外,当将代码写进自定义函数的时候,需要注意最后是return一个值而不是print。 def file_count(filename): with open(filename, 'r') as csvfile: print('Opening file: '+ filename) total=0 for line in csvfile: rowtotal=int(line[0])+int(line[2])+int(line[4]) print('Row total:'+str(rowtotal)) total=total+rowtotal print('Total in file '+ filename +' is '+ str(total)) return total; overallTotal = 0 for file in glob.glob('*.csv'): overallTotal = overallTotal + file_count(file) print('Overall total is', overallTotal) def中的if条件语句需要做的是决定return什么值 而不是print def near(a,b): if a < b*0.1: return('True') else: return('False')




 
 
 

コメント


  • Facebook
  • Twitter
  • LinkedIn

© 2022 par Ziyi Zhao.

bottom of page