现有一文本,每行一条数据,实现这行数据中有所要关键字则打出这行
import sys with open(sys.argv[1]) as alls: alls2 = [_.strip() for _ in alls] for _ in alls2: if sys.argv[2] in _: print _
一开始我是这么写的,后来觉得既不美观,速度又慢(运行花了2.31 s),进行了改写
with open( sys.argv[1] ) as alls: results = [ _.strip() for _ in alls if sys.argv[2] in _.strip() ] print '\n'.join( results )
运行耗时1.54 s,快了34%,效果不错
<pre name="code" class="python">with open( sys.argv[1] ) as alls: results = [ _.strip() for _ in alls if sys.argv[2] in _.strip() ]
for result in results: print result
print '\n'.join( results )
打出时太快,没有瀑布的感觉,改成
for result in results: print result
运行时间1.59 s居然慢了
后来用map函数改写
def fetch( _ ): _2 = _.strip() global searchP if searchP in _2: pass#print _2
map( fetch, list)
居然更慢了,耗时2 s
用上虚拟函数吧
x = map( lambda _: _.strip() if searchP in _.strip() else None, alls )
噩梦啊,更慢了 2.1 s
最后兼顾美观与速度,用了filter函数
xs = filter( lambda _: True if searchP in _.strip() else False, alls ) for x in xs: if x: print x,
耗时1.67 s,虽然还没传统的快,但技巧性已经提高了,效率就先放下吧。
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-06 09:07:19