小例子看python缩减代码

来源:互联网 发布:linux snmp 流量监控 编辑:程序博客网 时间:2024/05/21 10:44

问题:  寻找文件最长的行。


第一版核心代码:

f = open('/etc/motd', 'r')

longest = 0

while True:

    linelen = len(f.readline().strip())

    if not linelen:

        break

    if linelen > longest:

        longest = linelen

f.close()

return longest


第二版核心代码:(for循环+尽早释放文件句柄)

f = open('/etc/motd', 'r')

longest = 0

allLines = f.readlines()

f.close()

for line in allLines:

    linelen = len(line.strip())

    if linelen > longest:

        longest = linelen

return longest


第三版核心代码: (列表推导(解析))

f = open('/etc/motd', 'r')

longest = 0

allLines =  [x.strip() for x in f.readlines()]

f.close()

for line in allLines:

    linelen = len(line)

    if linelen > longest:

        longest = linelen

return longest


第四版核心代码: (利用迭代器+max()内建函数)

f = open('/etc/motd', 'r')

allLineLens = [len(x.strip()) for x in f]

f.close()

return max(allLineLens)


第五版核心代码: (生成器表达式优化内存)

f = open('/etc/motd', 'r')

longest  = max(len(x.strip()) for x in f)

f.close()

return max(longest)


最终boss版核心代码:(文件操作默认读, python自动关闭文件)

return max(len(x.strip()) for x in open('/etc/motd'))





例子和代码来自于《python核心编程》