Python高级应用实例对比:高效计算大文件中的最长行的长度
前2种方法主要用到了列表解析,性能稍差,而最后一种使用的时候生成器表达式,相比列表解析,更省内存
列表解析和生成器表达式很相似:
列表解析
[exprforiter_variniterableifcond_expr]
生成器表达式
(exprforiter_variniterableifcond_expr)
方法1:最原始
longest=0
f=open(FILE_PATH,"r")
allLines=[line.strip()forlineinf.readlines()]
f.close()
forlineinallLines:
linelen=len(line)
iflinelen>longest:
longest=linelen
方法2:简洁
f=open(FILE_PATH,"r") allLineLens=[len(line.strip())forlineinf] longest=max(allLineLens) f.close()
缺点:一行一行的迭代f的时候,列表解析需要将文件的所有行读取到内存中,然后生成列表
方法3:最简洁,最节省内存
f=open(FILE_PATH,"r") longest=max(len(line)forlineinf) f.close()
或者
printmax(len(line.strip())forlineinopen(FILE_PATH))
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短