Open-AutoGLM性能优化全攻略,快速掌握AI驱动开发的黄金法则
2025/12/25 9:54:40
生成器表达式是一种压缩形式,它将更高级的生成器语法压缩到一行中。以日志文件处理为例,若要从输出文件中删除WARNING列(因为该文件仅包含警告信息,此列冗余),有多种实现方式。
import sys # generator expression inname, outname = sys.argv[1:3] with open(inname) as infile: with open(outname, "w") as outfile: warnings = ( l.replace("\tWARNING", "") for l in infile if "WARNING" in l ) for l in warnings: outfile.write(l)这种方式可读性较好,但不宜使表达式过于复杂。
with open(inname) as infile: with open(outname, "w") as outfile: for l in infile: