码迷,mamicode.com
首页 > 编程语言 > 详细

python题目练习

时间:2015-07-30 23:42:37      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:sort

1、随机生成一个大文件(5G以上),查找里面内容最长的N(N>5)行,并打印出来

[root@saltstack-ui ~]# cat gen_large_file.py
import os
with open("a.txt", "w") as f:
    f.write(os.urandom(1024*1024*1024*5)) # 产生一个5G大小的文件,里面都是随机内容,耗时长,有待改进
    
[root@saltstack-ui ~]# cat find_large_line.py  # 利用list sort来排列,然后打印最长的5行
log_path=‘a.txt‘
N=5

with open(log_path) as f:
    a = [ line for line in f ]
    a.sort(key=lambda x:len(x),reverse=True)
    for i in range(N):
        print "%d %s" %(i+1,a[i])

本文出自 “the-way-to-cloud” 博客,请务必保留此出处http://iceyao.blog.51cto.com/9426658/1680157

python题目练习

标签:sort

原文地址:http://iceyao.blog.51cto.com/9426658/1680157

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!